gpt4 book ai didi

python - 从列表定义函数

转载 作者:太空狗 更新时间:2023-10-29 21:33:36 24 4
gpt4 key购买 nike

假设我有一个字符串列表:obj = ['One','Two','Three'],我如何才能将此列表中的每个值转换为一个函数,其中他们都执行非常相似的功能?例如:

def one():
print("one")

def two():
print("two")

def three():
print("three")

现在我知道你可以预先定义函数并使用字典(如下所示),但是如果我想创建很多函数,那么这样做会花费很多代码,因此我想找出答案如果有更短的方法我可以解决这个问题。

import tkinter as tk

def one():
print("one")

def two():
print("two")

def three():
print("three")

obj = ['One','Two','Three']
func = {'One': one, 'Two': two, 'Three': three}

def create_btn():
btns = {}
for i in obj:
text = i
for col in range(1):
for row in range(len(obj)):
btns[row, col] = tk.Button(canvas, text=str(text),
command=func[i]).grid(column=col,
row=row)
btns[row, col] = canvas.create_window(50, row,
window = btns[row, col])
canvas.pack()


root = tk.Tk()
root.geometry = ("750x600")

btn_frame = tk.Frame(root)
canvas = tk.Canvas(root)

create_btn()
root.mainloop()

最佳答案

使用闭包:

>>> def print_me(string):
... def inner():
... print(string)
... return inner
...
>>> functions = [print_me(s) for s in obj]
>>> functions[0]()
One
>>> functions[1]()
Two
>>> functions[2]()
Three

也许 dict 会更方便:

>>> functions = {s:print_me(s) for s in obj}
>>> functions['One']
<function print_me.<locals>.wrapper at 0x102078bf8>
>>> functions['One']()
One
>>>

关于python - 从列表定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41900300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com