[英]Calling a function multiple times consecutively with different arguments in Python (3.x)?
我有一段看起來像這樣的代碼:
myfunction(a, b, c)
myfunction(d, e, f)
myfunction(g, h, i)
myfunction(j, k, l)
參數的數量不會改變,但必須每次使用不同的值連續調用該函數。 這些值不是自動生成的,而是手動輸入的。 是否有內聯解決方案可以在不創建函數來調用此函數的情況下執行此操作? 就像是:
myfunction(a, b, c)(d, e f)(g, h, i)(j, k, l)
任何幫助表示贊賞。 提前致謝!
簡單,使用元組解包
tripples = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'm')]
for tripple in tripples:
print(myfunction(*tripple))
我很驚訝沒有人提到map
map(func, iter)
它將iter
中的每個可迭代對象映射到第一個參數中傳遞的func
。
對於您的用例,它應該看起來像
map(myfunction, *zip((a, b, c), (d, e, f), (g, h, i), (j, k, l)))
嗨,我不確定這是否是最 Pythonic 的方式,但是如果您在列表中定義了參數,則可以在循環中調用該函數,並從列表的開頭刪除 n 參數:
看看示例代碼:
def myfunction(x1,x2,x3):
return x1+x2+x3
arglist = [1,2,3,4,5,6,7,8,9]
for _ in range(3):
print myfunction(arglist[_+0],arglist[_+1],arglist[_+2])
# remove used arguments from the list
arglist= arglist[2:]
你可以在這里濫用列表理解
[myfunction(*item) for item in ((a, b, c), (d, e, f), (g, h, i), (j, k, l))]
我想你想做的是這樣的......
myfunction(myfunction(d, e, f), myfunction(g, h, i), myfunction(j, k, l))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.