Python程序连接列表中的每个元素
给定 2 个列表,跨列表执行所有字符串的串联。
Input : test_list1 = [“gfg”, “is”, “best”], test_list2 = [“love”, “CS”]
Output : [‘gfg love’, ‘gfg CS’, ‘is love’, ‘is CS’, ‘best love’, ‘best CS’]
Explanation : All strings are coupled with one another.
Input : test_list1 = [“gfg”, “best”], test_list2 = [“love”, “CS”]
Output : [‘gfg love’, ‘gfg CS’, ‘best love’, ‘best CS’]
Explanation : All strings are coupled with one another.
方法#1:使用列表理解
在这种情况下,我们使用列表理解形成对,然后使用另一个列表理解执行连接任务。
Python3
# Python3 code to demonstrate working of
# All elements concatenation across lists
# Using list comprehension
# initializing lists
test_list1 = ["gfg", "is", "best"]
test_list2 = ["love", "CS"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# forming pairs
temp = [(a, b) for a in test_list1 for b in test_list2]
# performing concatenation
res = [x + ' ' + y for (x, y) in temp]
# printing result
print("The paired combinations : " + str(res))
Python3
# Python3 code to demonstrate working of
# All elements concatenation across lists
# Using product() + list comprehension
from itertools import product
# initializing lists
test_list1 = ["gfg", "is", "best"]
test_list2 = ["love", "CS"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# concatenation using formatting and pairing using product
res = ['%s %s' % (ele[0], ele[1]) for ele in product(test_list1, test_list2)]
# printing result
print("The paired combinations : " + str(res))
输出:
The original list 1 is : [‘gfg’, ‘is’, ‘best’]
The original list 2 is : [‘love’, ‘CS’]
The paired combinations : [‘gfg love’, ‘gfg CS’, ‘is love’, ‘is CS’, ‘best love’, ‘best CS’]
方法 #2:使用product() + 列表理解
在这里,我们使用 product() 执行形成组合的任务,列表理解执行连接任务。
蟒蛇3
# Python3 code to demonstrate working of
# All elements concatenation across lists
# Using product() + list comprehension
from itertools import product
# initializing lists
test_list1 = ["gfg", "is", "best"]
test_list2 = ["love", "CS"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# concatenation using formatting and pairing using product
res = ['%s %s' % (ele[0], ele[1]) for ele in product(test_list1, test_list2)]
# printing result
print("The paired combinations : " + str(res))
输出:
The original list 1 is : [‘gfg’, ‘is’, ‘best’]
The original list 2 is : [‘love’, ‘CS’]
The paired combinations : [‘gfg love’, ‘gfg CS’, ‘is love’, ‘is CS’, ‘best love’, ‘best CS’]