list1=[1,2,3]
list2=['a','b','c']
list3=[4,'e']
combination = [(i,j,k) for i in list1for j in list2for kin list3]
print结果:[(1, 'a', 4), (1, 'a', 'e'), (1, 'b', 4), (1, 'b', 'e'), (1, 'c', 4), (1, 'c', 'e'), (2, 'a', 4), (2, 'a', 'e'), (2, 'b', 4), (2, 'b', 'e'), (2, 'c', 4), (2, 'c', 'e'), (3, 'a', 4), (3, 'a', 'e'), (3, 'b', 4), (3, 'b', 'e'), (3, 'c', 4), (3, 'c', 'e')]
当列表个数不定时,先根据需求生成字符串,然后采用eval()函数将字符串转换为可执行命令。
import string
maxKind =list(string.ascii_letters) # 26个小写字母和26个大写字母列表,假设最多52种
cc ='a'
dd ='for a in listA[0]'
listA = [[列表1], [列表2], [列表3], [列表4]]
for i in range(1, len(listA)):
cc = cc +',' + maxKind[i]
dd = dd +' for ' +str(maxKind[i]) +' in list' +str([i])
print('(' + cc +')' +' ' + dd) # (a,b,c,d) for a in listA[0] for b in listA[1] for c in listA[2] for d in listA[3]
ee='[(' + cc +')' +' ' + dd +']'
combination =eval(ee)
网友评论