簡體   English   中英

在迭代可變數量的索引時調用表達式中的索引(Python)

[英]Calling indices in an expression while iterating over a variable number of indices (Python)

我想迭代列表長度給定的可變數量的索引,使用列表中的值作為范圍。 此外,我想在我的表達式中調用索引。

例如,如果我有一個列表 [2,4,5],我會想要類似:

import itertools

for i0, i1, i2 in itertools.product(range(2),range(4),range(5)):
    otherlist[i0]**i0 + otherlist[i2]**i2

我能得到的最接近的是

for [i for i in range(len(mylist))] in itertools.product(*[range(i) for i in mylist]):
    

但我不知道如何從這里調用索引。

你已經很親近了。 當您使用for語句時,我發現最好保持目標列表簡單並在 for 循環中訪問目標列表的組件; 在此代碼中,由 product() 生成的元組。

import itertools

mylist = [2,4,5]
otherlist = list(range(5))

for t in itertools.product(*[range(i) for i in mylist]):
    print(otherlist[t[0]]**t[0] + otherlist[t[2]]**t[2])
# 2
# 2
# 5
# 28
# 257
# ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM