![](/img/trans.png)
[英]In Python how do I use list comprehensions to iterate through a list of lists?
[英]how do I iterate through a list of lists
我試圖找出如何遍歷列表列表並從左到右記錄列表中所有可能的組合。 第一個列表將始終是組合的第一個位置,第二個列表將是第二個位置,依此類推。
假設第一個列表始終是同一字母,我將如何獲得字母的所有可能組合。 到目前為止,我的代碼確實隔離了第一組,但是我很難將其余的添加到列表中以創建組合。
listoflists = [[a,b,c,d][e,f,g][h,i]]
for i in range(len(listoflists[]):
for j in range(len(listoflists[i])):
if(i==0):
print(listoflists[i][j])
newlist[i].append([listoflists[i][j]])
else:
print(i)
print(listoflists[i][j])
#newlist[[i[j]].append([listoflists[i][j]])
代碼的最后一行將引發錯誤,並且打印語句已在此處進行調試。 所以我將如何使用for循環准確獲取列表列表的所有組合
該過程稱為笛卡爾積 :
在數學中,笛卡爾積是一種數學運算,它從多個集合中返回一個集合(或乘積集合或簡單地乘積)。 也就是說,對於集合A和B,笛卡爾乘積A×B是所有有序對(a,b)的集合,其中a∈A和b∈B。
在python中已經有一個庫函數,即itertools.product
:
從文檔 :
itertools.product(* iterables [,repeat])輸入可迭代對象的笛卡爾積。
等效於生成器表達式中的嵌套for循環。 例如,乘積(A,B)與(對於B中的y對A中的x的((x,y))返回相同。
將其應用於列表時,您將獲得所需的結果:
>>> import itertools
>>> ll = [["a","b","c","d"], ["e","f","g"], ["h","i"]]
>>> list(itertools.product(*ll))
[('a', 'e', 'h'), ('a', 'e', 'i'), ('a', 'f', 'h'), ('a', 'f', 'i'), ('a', 'g', 'h'), ('a', 'g', 'i'), ('b', 'e', 'h'), ('b', 'e', 'i'), ('b', 'f', 'h'), ('b', 'f', 'i'), ('b', 'g', 'h'), ('b', 'g', 'i'), ('c', 'e', 'h'), ('c', 'e', 'i'), ('c', 'f', 'h'), ('c', 'f', 'i'), ('c', 'g', 'h'), ('c', 'g', 'i'), ('d', 'e', 'h'), ('d', 'e', 'i'), ('d', 'f', 'h'), ('d', 'f', 'i'), ('d', 'g', 'h'), ('d', 'g', 'i')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.