oduncu90
oduncu90

Reputation: 45

Python List Comprehension With List of List

I have a list of list (Actual list is longer):

a = [[1, 2], [5, 8], [10, 4], [15, 9]]

I need to use this list in list comprehension. For the first loop 1 and 2 will be used as i and j. For the second loop 5 and 8 will be used as i and j. And so on.

Following code is not correct, but how can I make it work? I do not want to split the list. Very very little computational cost is important.

[some_work_with(i, j) for i, j in zip(a[][0], a[][1])]

Some work could be print(i, j).

Upvotes: 0

Views: 48

Answers (3)

Jan Alexander
Jan Alexander

Reputation: 165

Why not simply

[some_work(pair[0], pair[1]) for pair in a]

for example

[f'i : {pair[0]} and j : {pair[1]}' for pair in a]

This will result in:

['i : 1 and j : 2', 'i : 5 and j : 8', 'i : 10 and j : 4', 'i : 15 and j : 9']

Upvotes: 0

Synthaze
Synthaze

Reputation: 6090

def func(i,j):
    return [i-1, j+1]

a = [[1, 2], [5, 8], [10, 4], [15, 9]]

print ([func(x[0], x[1]) for x in a])

Output:

[[0, 3], [4, 9], [9, 5], [14, 10]]

You can also use this syntax if you prefer:

print ([func(i, j) for i, j in a])

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

You don't need zip here, just unpack the elements as you are iterating over them

[some_work_with(i, j) for i, j in a]

Upvotes: 1

Related Questions