Ketcomp
Ketcomp

Reputation: 454

In Python how do I use list comprehensions to iterate through a list of lists?

I have a list of tuples with values and co-ordinates of 11 points

dotted_array = [(0, 0, '.'), (2, 0, '.'), (3, 0, '.'), (0, 1, '.'), (2, 1, '.'), (0, 2, '.'), (2, 2, '.'), (3, 2, '.'), (0, 3, '.'), (2, 3, '.'), (3, 3, '.')]

I have a list of 5 lists:

list_of_signs = [['+', '+', '-', '+', '+', '+', '+', '-', '+', '+', '-'], ['+', '+', '-', '+', '-', '+', '+', '-', '+', '+', '-'], ['+', '+', '-', '+', '+', '+', '+', '-', '+', '+', '-'], ['+', '-', '-', '+', '+', '+', '+', '-', '+', '+', '-'], ['+', '+', '-', '+', '+', '+', '+', '-', '+', '+', '-']]

Each list in that list consists of i values of +/-. These +/- values correspond to the new value of the list element in dotted_array.

list_of_signs[] = [+,-,+,-,+.....11 values in each 'list_of_signs[]']

This is the expected output by combining the 'value' from list_of_signs[] and co-ordinates from dotted_array[]

coord_list = [[(0, 0, '+'), (2, 0, '+'), (3, 0, '-'), (0, 1, '+'), (2, 1, '+'), (0, 2, '+'), (2, 2, '+'), (3, 2, '-'), (0, 3, '+'), (2, 3, '+'), (3, 3, '-')], 4 More such lists ]

Currently I am:

coord_list= [(x[0],x[1],list_of_signs[0][0]) for x in dotted_array]

To get:

[(0, 0, '+'), (2, 0, '+'), (3, 0, '+'), (0, 1, '+'), (2, 1, '+'), (0, 2, '+'), (2, 2, '+'), (3, 2, '+'), (0, 3, '+'), (2, 3, '+'), (3, 3, '+')]

This output is not only wrong, but also not general. How do I generalize this for all list_of_signs?

Upvotes: 4

Views: 712

Answers (3)

freegnu
freegnu

Reputation: 813

dotted = zip(range(1,22,2),range(2,23,2),'.'*11)
signs = ['+-+-+-+-+-+']*5
print [(dotted[n][:-1]+(i,)) for s in signs for n,i in enumerate(s)]

Upvotes: 0

Anand S Kumar
Anand S Kumar

Reputation: 90889

Is this what you want? -

>>> dotted_array = [(1,2,'.'), (4,5,'.'),(1,2,'.'), (4,5,'.'),(1,2,'.'), (4,5,'.')]
>>> list_of_signs = [['+','-','-','+','+','-'],['-','-','+','+','+','-']]


>>> coord_list = [[(x[0][0],x[0][1],x[1]) for x in zip(dotted_array,s)] for s in list_of_signs]


>>> coord_list
[[(1, 2, '+'), (4, 5, '-'), (1, 2, '-'), (4, 5, '+'), (1, 2, '+'), (4, 5, '-')], [(1, 2, '-'), (4, 5, '-'), (1, 2, '+'), (4, 5, '+'), (1, 2, '+'), (4, 5, '-')]]

zip function combines the lists it receives as parameter at each index so ith index of returned list(or iterator) of zip would be a tuple of ith element of first array and then ith element of second array , so on.

Upvotes: 5

sinhayash
sinhayash

Reputation: 2803

Let me know if it works:

dotted_array = [(1,2,'.'), (4,5,'.')]
list_of_signs = [['+','-'],['-','-']]

coord_list = []
for idx1, list_of_sign in enumerate(list_of_signs):
    mylist = []
    for idx2, tup in enumerate(dotted_array):
        mylist += [(tup[0],tup[1],list_of_signs[idx1][idx2]) ]
    coord_list += mylist

print coord_list

Writing that in one line would be fun.

Give a valid input for both arrays and the expected output for that.

Upvotes: 0

Related Questions