简体   繁体   中英

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

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

You can use itertools.combinations to get all possible pairs

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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