Python – 将列表拆分为所有可能的元组对
给定一个列表,任务是编写一个可以将其拆分为所有可能的元组对组合的Python程序。
Input : test_list = [4, 7, 5, 1, 9]
Output : [[4, 7, 5, 1, 9], [4, 7, 5, (1, 9)], [4, 7, (5, 1), 9], [4, 7, (5, 9), 1], [4, (7, 5), 1, 9], [4, (7, 5), (1, 9)], [4, (7, 1), 5, 9], [4, (7, 1), (5, 9)], [4, (7, 9), 5, 1], [4, (7, 9), (5, 1)], [(4, 7), 5, 1, 9], [(4, 7), 5, (1, 9)], [(4, 7), (5, 1), 9], [(4, 7), (5, 9), 1], [(4, 5), 7, 1, 9], [(4, 5), 7, (1, 9)], [(4, 5), (7, 1), 9], [(4, 5), (7, 9), 1], [(4, 1), 7, 5, 9], [(4, 1), 7, (5, 9)], [(4, 1), (7, 5), 9], [(4, 1), (7, 9), 5], [(4, 9), 7, 5, 1], [(4, 9), 7, (5, 1)], [(4, 9), (7, 5), 1], [(4, 9), (7, 1), 5]]
Explanation : All pairs partitions are formed.
Input : test_list = [4, 7, 5, 1]
Output : [[4, 7, 5, 1], [4, 7, (5, 1)], [4, (7, 5), 1], [4, (7, 1), 5], [(4, 7), 5, 1], [(4, 7), (5, 1)], [(4, 5), 7, 1], [(4, 5), (7, 1)], [(4, 1), 7, 5], [(4, 1), (7, 5)]]
Explanation : All pairs partitions are formed.
方法:使用切片和递归
在这里,我们从第一个元素开始创建所有对,并使用递归将多个元素通过适当的分区转换为对。
Python3
def pairings(test_list):
if len(test_list) <= 1:
return [test_list]
# keeping 1st element and attaching every element with it
parts = [[test_list[0]] + ele for ele in pairings(test_list[1:])]
for idx in range(1, len(test_list)):
# pairing all possible from second element
parts.extend([[(test_list[0], test_list[idx])] +
ele for ele in pairings(test_list[1: idx]
+ test_list[idx + 1:])])
return parts
# initializing list
test_list = [4, 7, 5, 1]
# printing original list
print("The original list is : " + str(test_list))
# calling util. function
res = pairings(test_list)
# printing result
print("Created partitions : " + str(res))
输出:
The original list is : [4, 7, 5, 1]
Created partitions : [[4, 7, 5, 1], [4, 7, (5, 1)], [4, (7, 5), 1], [4, (7, 1), 5], [(4, 7), 5, 1], [(4, 7), (5, 1)], [(4, 5), 7, 1], [(4, 5), (7, 1)], [(4, 1), 7, 5], [(4, 1), (7, 5)]]