📌  相关文章
📜  Python程序连接列表中的每个元素

📅  最后修改于: 2022-05-13 01:55:11.049000             🧑  作者: Mango

Python程序连接列表中的每个元素

给定 2 个列表,跨列表执行所有字符串的串联。

方法#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))


输出:

方法 #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))

输出: