簡體   English   中英

Python如何結合列表的每個元素

[英]Python How combine each element of a list

我有一個這樣的清單:
list=[0.2, 0.3, 0.5, 0.1, 0.7, 0.9]我要合並如下:

[[0.2,0.3][0.2,0.5][0.2,0.1][0.2,0.7]
[0.2,0.9][0.3,0.5][0.3,0.1][0.3,0.7]
[0.3,0.9][0.5,0.1][0.5,0.7][0.5,0.9]
[0.1,0.7][0.1,0.9][0.7][0.9]]

但我想到達此列表:

[[0.2 0.3, 0.5 ][0.2 0.3 0.5, 0.1]...[0.2 0.3 0.5 0.1 0.7, 0.9]]

我的代碼:

listOne=[0.2, 0.3, 0.5, 0.1, 0.7, 0.9]
listTwo=[]
i=0; j=0; aux=0;
while i<len(listOne):
    while j<len(listOne):
        print listOne[j]        
        listTwo.append(listOne[i])
        listTwo.append(listOne[j])
        j+=1
    i+=1
print listTwo

這是我的輸出清單

[0.2, 0.2, 0.2, 0.3, 0.2, 0.5, 0.2, 0.1 ]

您可以在此處使用itertools.combinations 我不明白你的期望。

from itertools import combinations

res = [i for i in combinations(list,2)] #please dont provide variable name as list
>>>res
[(0.2, 0.3),
 (0.2, 0.5),
 (0.2, 0.1),
 ... ]

您可以通過使用列表理解來實現:

listOne = [0.2, 0.3, 0.5, 0.1, 0.7, 0.9]
listTwo = [listOne[:upto] for upto in range(3, len(listOne) + 1)]
print listTwo

輸出:

[[0.2, 0.3, 0.5], [0.2, 0.3, 0.5, 0.1], [0.2, 0.3, 0.5, 0.1, 0.7], [0.2, 0.3, 0.5, 0.1, 0.7, 0.9]]

我不太了解您真正想要做什么,但是我想您想找到列表的可能子集。

因此,您可以從itertools使用電源集: https ://docs.python.org/2/library/itertools.html

def powerset(s):

    '''powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3)(2,3) (1,2,3)'''

    subset =  itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s) + 1))
    return [list(x) for x in subset]

myList = [0.2, 0.3, 0.5, 0.1, 0.7, 0.9]
subsets = powerset(myList)

如果只想保留所有長度大於3的子集,則可以使用subset.remove()刪除元素,或者可以使用filter()函數:

subsets = filter(lambda x: len(x)>=3, subsets)

這樣您將獲得想要的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM