[英]pythonic way for nested loops checking items against two or more list
I want to check items against two lists in python which are again put in the one big list In my codes , combinedList is big list and row1 and row2 are sub-list. 我想对照python中的两个列表检查项目,这些列表再次放在一个大列表中。在我的代码中,CombinedList是大列表,而row1和row2是子列表。
I need to check items in row1 and row2 against each other. 我需要相互检查row1和row2中的项目。 I got rough idea in psudo code however , since im new to python . 但是,由于python是我的新手,所以我在psudo代码中有一个大概的主意。 is there any good codes for checking against two list for their item without repeating the same pair more than once? 是否有任何良好的代码可用来检查两个项目的清单,而不会重复同一对?
row1 = [a,b,c,d,....]
row2 = [s,c,e,d,a,..]
combinedList = [row1 ,row2]
for ls in combinedList:
**for i=0 ; i < length of ls; i++
for j= i+1 ; j <length of ls; j++
do something here item at index i an item at index j**
I guess you're looking for itertools.product
: 我猜你在找itertools.product
:
>>> from itertools import product
>>> row1 = ['a', 'b', 'c', 'd']
>>> row2 = ['s', 'c', 'e', 'd', 'a']
>>> seen = set() #keep a track of already visited pairs in this set
>>> for x,y in product(row1, row2):
if (x,y) not in seen and (y,x) not in seen:
print x,y
seen.add((x,y))
seen.add((y,x))
...
a s
a c
a e
a d
a a
b s
b c
b e
b d
b a
c s
c c
c e
c d
d s
Update: 更新:
>>> from itertools import combinations
>>> for x,y in combinations(row1, 2):
... print x,y
...
a b
a c
a d
b c
b d
c d
Use the zip()
built-in function to pair values of two lists: 使用zip()
内置函数来配对两个列表的值:
for row1value, row2value in zip(row1, row2):
# do something with row1value and row2value
If you wanted to combine each element from row1 with each element of row2 instead (the product of the two lists), use itertools.product()
instead: 如果您想将row1中的每个元素与row2中的每个元素(两个列表的乘积)组合起来,请使用itertools.product()
代替:
from itertools import product
for row1value, row2value in product(row1, row2):
# do something with row1value and row2value
zip()
simply pairs up the lists producing len(shortest_list)
items, product()
pairs up each element in one list with each element in the other, producing len(list1)
times len(list2)
items: zip()
只是将产生len(shortest_list)
项的列表配对, product()
将一个列表中的每个元素与另一个列表中的每个元素配对,产生len(list1)
乘以len(list2)
项:
>>> row1 = [1, 2, 3]
>>> row2 = [9, 8, 7]
>>> for a, b in zip(row1, row2):
... print a, b
...
1 9
2 8
3 7
>>> from itertools import product
>>> for a, b in product(row1, row2):
... print a, b
...
1 9
1 8
1 7
2 9
2 8
2 7
3 9
3 8
3 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.