簡體   English   中英

將多個for循環鏈接在一起

[英]Chaining multiple for loops together into one

我從文件中讀取了兩個列表,它們看起來與此類似:

list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 0]

然后,我有一個for循環,需要調用這兩個列表:

res = []
for i in list1:
    for x in list2:
        if i + x * 2 == 10:
             res.append((i,x))

我想要做的是將for循環鏈接到一個循環中,這樣它就只會遍歷每個數字一次,例如:

res = []
for i in list1 and x in list2:
    if i + x * 2 == 10:
        res.append((i,x))

現在執行上述操作,將輸出未定義x的錯誤:

>>> list1 = [1, 2, 3, 4, 5]
>>> list2 = [6, 7, 8, 9, 0]
>>> res = []
>>> for i in list1 and x in list2:
...     if i + x * 2 == 10:
...         res.append((i,x))
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> 

我該如何用Python做到這一點?

試試zip itertools.product

import itertools
...
for i, x in itertools.product(list1, list2):
   if i + x * 2 == 10:
       res.append((i, x))

我要做的是使用range循環,即循環可能的索引而不是元素。 當然,您必須確保列表的長度相同,但這確實有幫助。 在您的情況下實施:

res = []
for index in range (len (list1)):
    if list1 [index] + list2 [index] * 2 == 10: res.append ((list1 [index], list2 [index]))

而且,如果我敢,我會一口氣:

res = [(list1 [index], list2 [index]) for index in range (len (list1)) if list1 [index] + list2 [index] * 2 == 10]

請記住,這僅是交叉搜索列表,並且不會遍歷list2中list1中的每個元素。

暫無
暫無

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

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