gpt4 book ai didi

Python:调用具有不同数量参数的函数

转载 作者:行者123 更新时间:2023-11-30 23:32:50 25 4
gpt4 key购买 nike

我想编写一个函数,将字典转换为 Gtk-ListStore,其中 Gtklist-store 应该有 n 列,第一个是字典的键和值,其余的是空字符串。 N 应由用户给出。

ListStore 的构造函数需要列的类型。如何以正确的数字指定它们?

下面是仅支持 2 或 3 列的函数来演示该问题:

def dict2ListStore(dic, size=2):
if size == 2:
liststore = Gtk.ListStore(str, str)
for i in dic.items():
liststore.append(i)
return liststore
elif size == 3:
liststore = Gtk.ListStore(str, str, str)
for i in dic.items():
l = list(i)
l.append("")
liststore.append(l)
return liststore
else:
print("Error!")
return

最佳答案

liststore = Gtk.ListStore(*([str] * size))

[str] * size 是一个包含 sizestr 重复项的列表。

func(*args) 是将序列 args 中包含的值作为多个参数传递的方法。

关于Python:调用具有不同数量参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19198520/

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