Python – 扩展连续元组
给定元组列表,连接连续的元组。
Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
Output : [(3, 5, 6, 7, 3, 2, 4, 3), (3, 2, 4, 3, 9, 4), (9, 4, 2, 3, 2)]
Explanation : Elements joined with their consecutive tuples.
Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3)]
Output : [(3, 5, 6, 7, 3, 2, 4, 3)]
Explanation : Elements joined with their consecutive tuples.
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们通过访问内部循环执行加入连续的任务。
Python3
# Python3 code to demonstrate working of
# Extend consecutive tuples
# Using loop
# initializing list
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2), (3, ), (3, 6)]
# printing original list
print("The original list is : " + str(test_list))
res = []
for idx in range(len(test_list) - 1):
# joining tuples
res.append(test_list[idx] + test_list[idx + 1])
# printing results
print("Joined tuples : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extend consecutive tuples
# Using zip() + list comprehension
# initializing list
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2), (3, ), (3, 6)]
# printing original list
print("The original list is : " + str(test_list))
# zip to combine consecutive elements
res = [a + b for a, b in zip(test_list, test_list[1:])]
# printing results
print("Joined tuples : " + str(res))
输出
The original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2), (3, ), (3, 6)]
Joined tuples : [(3, 5, 6, 7, 3, 2, 4, 3), (3, 2, 4, 3, 9, 4), (9, 4, 2, 3, 2), (2, 3, 2, 3), (3, 3, 6)]
方法 #2:使用 zip() + 列表理解
在此,我们使用 zip() 和切片构造连续列表,然后相应地形成对。
Python3
# Python3 code to demonstrate working of
# Extend consecutive tuples
# Using zip() + list comprehension
# initializing list
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2), (3, ), (3, 6)]
# printing original list
print("The original list is : " + str(test_list))
# zip to combine consecutive elements
res = [a + b for a, b in zip(test_list, test_list[1:])]
# printing results
print("Joined tuples : " + str(res))
输出
The original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2), (3, ), (3, 6)]
Joined tuples : [(3, 5, 6, 7, 3, 2, 4, 3), (3, 2, 4, 3, 9, 4), (9, 4, 2, 3, 2), (2, 3, 2, 3), (3, 3, 6)]