Python - 将列表与其他列表元素结合
给定两个列表,将列表与另一个列表的每个元素结合起来。
例子:
Input : test_list = [3, 5, 7], pair_list = [‘Gfg’, ‘is’, ‘best’]
Output : [([3, 5, 7], ‘Gfg’), ([3, 5, 7], ‘is’), ([3, 5, 7], ‘best’)]
Explanation : All lists paired with each element from other list.
Input : test_list = [3, 5, 7], pair_list = [‘Gfg’, ‘best’]
Output : [([3, 5, 7], ‘Gfg’), ([3, 5, 7], ‘best’)]
Explanation : All lists paired with each element from other list.
方法 #1:使用zip() + len() + list()
在这里,我们使用 zip() 将每个元素与其他列表的所有元素配对,使用 len() 并一次选择每个元素。
Python3
# Python3 code to demonstrate working of
# Combine list with other list elements
# Using zip() + len() + list()
# initializing list
test_list = [3, 5, 7, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing pair list
pair_list = ['Gfg', 'is', 'best']
# using zip() to pair element with pair list size
res = list(zip([test_list] * len(pair_list), pair_list))
# printing result
print("The paired list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Combine list with other list elements
# Using product()
from itertools import product
# initializing list
test_list = [3, 5, 7, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing pair list
pair_list = ['Gfg', 'is', 'best']
# product() performs pairing of elements
res = list(product([test_list], pair_list))
# printing result
print("The paired list : " + str(res))
输出:
The original list is : [3, 5, 7, 9]
The paired list : [([3, 5, 7, 9], ‘Gfg’), ([3, 5, 7, 9], ‘is’), ([3, 5, 7, 9], ‘best’)]
方法#2:使用product()
在此,我们使用 product() 对元素进行配对,并将每个列表与配对列表中的每个元素进行映射。
蟒蛇3
# Python3 code to demonstrate working of
# Combine list with other list elements
# Using product()
from itertools import product
# initializing list
test_list = [3, 5, 7, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing pair list
pair_list = ['Gfg', 'is', 'best']
# product() performs pairing of elements
res = list(product([test_list], pair_list))
# printing result
print("The paired list : " + str(res))
输出:
The original list is : [3, 5, 7, 9]
The paired list : [([3, 5, 7, 9], ‘Gfg’), ([3, 5, 7, 9], ‘is’), ([3, 5, 7, 9], ‘best’)]