📜  Python – 将元组添加到列表,反之亦然

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

Python – 将元组添加到列表,反之亦然

有时,在使用Python容器时,我们可能会遇到需要将一个容器与另一个容器相加的问题。此类问题可能在计算机科学和编程的许多数据域中发生。让我们讨论可以执行此任务的某些方式。
方法一:使用 +=运算符[list + tuple]
此运算符可用于连接带有元组的列表。在内部,它的工作类似于 list.extend(),它可以有任何可迭代的作为它的参数,在这种情况下是元组。

Python3
# Python3 code to demonstrate working of
# Adding Tuple to List and vice - versa
# Using += operator (list + tuple)
 
# initializing list
test_list = [5, 6, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing tuple
test_tup = (9, 10)
 
# Adding Tuple to List and vice - versa
# Using += operator (list + tuple)
test_list += test_tup
 
# printing result
print("The container after addition : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Adding Tuple to List and vice - versa
# Using tuple(), data type conversion [tuple + list]
 
# initializing list
test_list = [5, 6, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing tuple
test_tup = (9, 10)
 
# Adding Tuple to List and vice - versa
# Using tuple(), data type conversion [tuple + list]
res = tuple(list(test_tup) + test_list)
 
# printing result
print("The container after addition : " + str(res))


输出 :
The original list is : [5, 6, 7]
The container after addition : [5, 6, 7, 9, 10]


方法#2:使用tuple(),数据类型转换[tuple + list]
以下技术用于将列表添加到元组。必须将元组转换为列表并添加列表,最后将结果转换为元组。

Python3

# Python3 code to demonstrate working of
# Adding Tuple to List and vice - versa
# Using tuple(), data type conversion [tuple + list]
 
# initializing list
test_list = [5, 6, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing tuple
test_tup = (9, 10)
 
# Adding Tuple to List and vice - versa
# Using tuple(), data type conversion [tuple + list]
res = tuple(list(test_tup) + test_list)
 
# printing result
print("The container after addition : " + str(res))
输出 :
The original list is : [5, 6, 7]
The container after addition : (9, 10, 5, 6, 7)