data_person
data_person

Reputation: 4500

grouping list elements in python

list = [('a5', 1), 1, ('a1', 1), 0, 0]

I want to group the elements of the list into 3, if the second or third element is missing in the list 'None' has to appended in the corresponding location.

exepected_output = [[('a5', 1), 1,None],[('a1', 1), 0, 0]]

Is there a pythonic way for this? New to this, any suggestions would be helpful.

Upvotes: 1

Views: 126

Answers (2)

vesche
vesche

Reputation: 1860

Here's a slightly different approach from the other answers, doing a comparison on the type of each element and then breaking the original list into chunks.

li = [('a5', 1), 1, ('a1', 1), 0, 0]

for i in range(0, len(li), 3):
    if type(li[i]) is not tuple:
        li.insert(i, None)
    if type(li[i+1]) is not int:
        li.insert(i+1, None)
    if type(li[i+2]) is not int:
        li.insert(i+2, None)

print [li[i:i + 3] for i in range(0, len(li), 3)]

Upvotes: 2

trelltron
trelltron

Reputation: 577

As far as I am aware, the only way to get the result you want is to loop through your list and detect when you encounter tuples.

Example which should work:

temp = None
result = []
for item in this_list:
    if type(item) == tuple:
        if temp is not None:
            while len(temp) < 3:
                temp.append(None)
            result.append(temp)
        temp = []
    temp.append(item)

Edit: As someone correctly commented, don't name a variable list, you'd be overwriting the built in list function. Changed name in example.

Upvotes: 1

Related Questions