如何组合两个列表以获得以下包含元组的期望结果?

How to combine two lists to get the following desired result containing tuples?

我有两个列表:

a = ['apple', 'mango', 'pear']

b = ['ripe','raw','rotten']

如何获得以下元组结果列表:

[(('apple', 'mango', 'pear'), 'ripe'), (('apple', 'mango', 'pear'), 'raw'), (('apple', 'mango', 'pear'), 'rotten')]

你试过自己解决吗?

试试这个:-

c = []
for i in b:
    c.append((tuple(a), i)) 
print (c) 

通常的方法是使用列表理解:

>>> [(tuple(a), x) for x in b]
[(('apple', 'mango', 'pear'), 'ripe'), (('apple', 'mango', 'pear'), 'raw'), (('apple', 'mango', 'pear'), 'rotten')]

如果不一定是元组,也可以用zip:

>>> list(zip([a]*len(b), b))
[(['apple', 'mango', 'pear'], 'ripe'), (['apple', 'mango', 'pear'], 'raw'), (['apple', 'mango', 'pear'], 'rotten')]

在一行中试试这个:

[(tuple(a), i) for i in b]

输出将是:

[(('apple', 'mango', 'pear'), 'ripe'),
 (('apple', 'mango', 'pear'), 'raw'),
 (('apple', 'mango', 'pear'), 'rotten')]

list(itertools.product(a,b)) 将使用 A 中的元素。要将完整列表作为一个元素,您可以使用嵌套列表,如:

list(itertools.product([tuple(a)], b)

结果:

[(('apple', 'mango', 'pear'), 'ripe'), (('apple', 'mango', 'pear'), 'raw'), (('apple', 'mango', 'pear'), 'rotten')]

你可以试试这个:

a = ['apple', 'mango', 'pear']

b = ['ripe','raw','rotten']

list=[ ]
for i in b:
    k=((tuple((tuple(a),i))))
    list.append(k)

print(list)