list - python在元组列表内进行组合

我正在研究其他一些问题。我有以下列表


[(['1', '2', '3'], 'abc'), (['4', '5', '6'], 'xyz')]



输出应该如下


[('1', 'abc'), ('2', 'abc'), ('3', 'abc'), ('4', 'xyz'), ('5', 'xyz'), ('6', 'xyz')]



我的尝试首先是unlist里面的列表


l1=[ tuple(i[0])+(i[1],) for i in l ]


print (l1)


[('1', '2', '3', 'abc'), ('4', '5', '6', 'xyz')]



然后尝试itertools的产品,但是,它并没有给我所需的结果, 问题是'abc '被分解为'a ','b ','c '。


from itertools import product


[ list(product(i[:-1],i[-1])) for i in l1 ]



[[('1', 'a'),


 ('1', 'b'),


 ('1', 'c'),


 ('2', 'a'),


 ('2', 'b'),


 ('2', 'c'),


 ('3', 'a'),


 ('3', 'b'),


 ('3', 'c')],


 [('4', 'x'),


 ('4', 'y'),


 ('4', 'z'),


 ('5', 'x'),


 ('5', 'y'),


 ('5', 'z'),


 ('6', 'x'),


 ('6', 'y'),


 ('6', 'z')]]



时间:

只要将字符串包在单元格中,就可以使用 itertools.product,以便它作为单个元素处理,


from itertools import product



data = [(['1', '2', '3'], 'abc'), (['4', '5', '6'], 'xyz')]



combos = [combo for a, b in data for combo in product(a, [b])]


print(combos)


# [('1', 'abc'), ('2', 'abc'), ('3', 'abc'), ('4', 'xyz'), ('5', 'xyz'), ('6', 'xyz')]



使用列表推导:


L=[(['1', '2', '3'], 'abc'), (['4', '5', '6'], 'xyz')] 



In: [ (n,s) for l,s in L for n in l ] 


Out: 


[('1', 'abc'),


 ('2', 'abc'),


 ('3', 'abc'),


 ('4', 'xyz'),


 ('5', 'xyz'),


 ('6', 'xyz')]



就像你所写的:


rslt=[]


for l,s in L:


 for n in l:


 rslt.append((n,s))



来自itertools的产品正在按预期工作。问题是Python字符串是可迭代的,因此产品正在迭代字符串的元素。如果要将字符串视为单个元素,可以将它的放入列表中,并将列表输入到产品中,

你可以使用列表推导:


ls = [(['1', '2', '3'], 'abc'), (['4', '5', '6'], 'xyz')]


ls_new = [(a,b) for n,b in ls for a in n]


print(ls_new)



...