Angel
Angel

Reputation: 11

Python How combine each element of a list

I have a list like this:
list=[0.2, 0.3, 0.5, 0.1, 0.7, 0.9] I want to combine as next:

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

But i want reach this list:

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

My code:

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

This is my output list

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

Upvotes: 0

Views: 129

Answers (3)

xirururu
xirururu

Reputation: 5508

I don't really understand what you really want to do, but I guess, you want to find the possible subset of the list.

So you can use the powerset from the 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)

If you just want to keep all the subsets with length bigger than 3, you can delete the elements with subset.remove(), or you can use the filter() function:

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

So you will get the result what you want.

Upvotes: 0

itzMEonTV
itzMEonTV

Reputation: 20339

You can use itertools.combinations here. I didnt understand what you are expecting.

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),
 ... ]

Upvotes: 1

Carsten
Carsten

Reputation: 18446

You can accomplish that by using a list comprehension:

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

Output:

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

Upvotes: 0

Related Questions