簡體   English   中英

單個列表中可能的列表組合

[英]Possible Combination of Lists inside a Single List

給定清單

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

我希望輸出為 3 個不同的列表,如下所示

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

您可以使用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])]

要展平單個元素,只需映射它們並添加兩個列表

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

只需使用枚舉函數,

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