📜  Python – 将列表元素添加到元组列表

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

Python – 将列表元素添加到元组列表

有时,在使用Python元组时,我们可能会遇到需要将特定列表的所有元素添加到列表的所有元组的问题。此类问题可能出现在 Web 开发和日常编程等领域。让我们讨论一下可以完成此任务的某些方法。

方法 #1 : 使用列表推导 + “+”运算符
上述功能的组合可以用来解决这个问题。在此,我们使用“+”运算符执行将元组添加到列表的任务,并使用列表推导完成对所有元组的迭代。

Python3
# Python3 code to demonstrate working of
# Add list elements to tuples list
# Using list comprehension + "+" operator
 
# initializing list
test_list = [(5, 6), (2, 4), (5, 7), (2, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing list
sub_list = [7, 2, 4, 6]
 
# Add list elements to tuples list
# Using list comprehension + "+" operator
res = [sub + tuple(sub_list) for sub in test_list]
 
# printing result
print("The modified list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Add list elements to tuples list
# Using list comprehension + "*" operator
 
# initializing list
test_list = [(5, 6), (2, 4), (5, 7), (2, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing list
sub_list = [7, 2, 4, 6]
 
# Add list elements to tuples list
# Using list comprehension + "*" operator
res = [(*sub, *sub_list) for sub in test_list]
 
# printing result
print("The modified list : " + str(res))


输出 :
The original list is : [(5, 6), (2, 4), (5, 7), (2, 5)]
The modified list : [(5, 6, 7, 2, 4, 6), (2, 4, 7, 2, 4, 6), (5, 7, 7, 2, 4, 6), (2, 5, 7, 2, 4, 6)]


方法#2:使用列表理解+“*”运算符
上述功能的组合可以用来解决这个问题。在此,我们使用打包解包运算符“*”执行将列表添加到元组的任务。这是比上述方法更有效的方法。

Python3

# Python3 code to demonstrate working of
# Add list elements to tuples list
# Using list comprehension + "*" operator
 
# initializing list
test_list = [(5, 6), (2, 4), (5, 7), (2, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing list
sub_list = [7, 2, 4, 6]
 
# Add list elements to tuples list
# Using list comprehension + "*" operator
res = [(*sub, *sub_list) for sub in test_list]
 
# printing result
print("The modified list : " + str(res))
输出 :
The original list is : [(5, 6), (2, 4), (5, 7), (2, 5)]
The modified list : [(5, 6, 7, 2, 4, 6), (2, 4, 7, 2, 4, 6), (5, 7, 7, 2, 4, 6), (2, 5, 7, 2, 4, 6)]