简体   繁体   English

单个列表中可能的列表组合

[英]Possible Combination of Lists inside a Single List

Given List给定清单

[[1,2],[3,4],[5,6]]

I want output as 3 different list as follows我希望输出为 3 个不同的列表,如下所示

[1,2,3,4],[3,4,5,6],[1,2,5,6]

You can use itertools.combinations to get all possible pairs您可以使用itertools.combinations来获取所有可能的对

a = [[1, 2], [3, 4], [5, 6]]

>>> list(itertools.combinations(a, 2))
[([1, 2], [3, 4]), ([1, 2], [5, 6]), ([3, 4], [5, 6])]

To flatten the individual elements just map over them and add the two lists要展平单个元素,只需映射它们并添加两个列表

>>> list(map(lambda x: x[0] + x[1], itertools.combinations(a, 2)))
[[1, 2, 3, 4], [1, 2, 5, 6], [3, 4, 5, 6]]

Simply Use Enumerate Function,只需使用枚举函数,

>>> x=[[1,2],[3,4],[5,6]]

>>> z = [x[index-len(x)] + x[index+1 - len(x)] for index, rec in enumerate(x)]

>>> z

>>> [[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 1, 2]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM