我有一個功能,我需要基於一定的變量一定的參數,像這樣打電話:生成可變數量的用於函數調用的參數代碼
self.model = Gtk.ListStore(str for i in len(dictionary))
當然不工作因爲str for i in len(dictionary)
結果在一個列表中:[str, str, str, str]
雖然我總是可以爲每個替代方法編寫4行和一堆if語句,但必須有更好的方法來執行此操作。
我有一個功能,我需要基於一定的變量一定的參數,像這樣打電話:生成可變數量的用於函數調用的參數代碼
self.model = Gtk.ListStore(str for i in len(dictionary))
當然不工作因爲str for i in len(dictionary)
結果在一個列表中:[str, str, str, str]
雖然我總是可以爲每個替代方法編寫4行和一堆if語句,但必須有更好的方法來執行此操作。
重複同樣的值x倍只是一個int乘以:
Gtk.ListStore(*[str]*len(dictionary))
對於任意波形發生器,把明星生成器之前,將它解開:
Gtk.ListStore(*(x for bar in spam))
注意,有沒有需要一個臨時列表。
也許你可以使用*語法?
self.model = Gtk.ListStore(*[str for i in len(dictionary)])
*解包列表並將每個元素作爲單獨的參數傳遞給函數。
太棒了!因爲整數不可迭代(doh) –
yes(* [str(x)for x in range(len(dict))]]應該可以工作,但是可能需要補充說我已經調用了'range(len(dictionary))'你應該知道liststore就像一個python list.Avoiding dict和使用元組列表可能會更有效率。 – cox
如果您要調用的函數使用*args
,那麼您可以使用我相信稱爲splat運算符 - *
。
例子:
def f(*arbitrary_amount_of_arguments):
for i in arbitrary_amount_of_arguments:
print(i)
>>> f("a", "b", "c")
a
b
c
>>> f(*[1, 2, 3, 4, 5, 6, 7])
1
2
3
4
5
6
7
或者在具體的例子:
self.model = Gtk.ListStore(*(str for i in range(len(dictionary))))
我也想問題,如果你想通過內置的字符串類str
爲我的range(LEN(詞典))。
編輯:self.model = Gtk.ListStore(*(str for _ in enumerate(dictionary)))
或self.model = Gtk.ListStore(*[[str] * len(dictionary))
可能比我以前的建議更好,因爲他們更Pythonic。
這是我用例中最乾淨的。 –
第一個例子是列表理解而不是生成器,還是其他的東西? –
@JV:第一個例子只是一個乘法運算符。當應用於一個序列(列表,字符串等)時,它會重複這個序列x次:http://docs.python.org/2/reference/expressions.html#binary-arithmetic-operations – georg