I Sui
I Sui

Reputation: 13

Problem in list comprehension output in python

I have the following liste

d=[[(1.0,1.1,1223),(2.0,1.1,1224)],[(3.0,1.1,1222),(4.0,1.1,1222)],[(5.0,1.1,1222),(1.0,1.1,1222)]]

I want to obtain the following result using list comprehension:

[[(1.0, 1.1), (2.0, 1.1)], [(3.0, 1.1), (4.0, 1.1)], [(5.0, 1.1), (1.0, 1.1)]]

I have done this

g= [d[i][y][:2] for i in range(len(d)) for y in range(len(d[i]))]

However, i got this output:

[(1.0, 1.1), (2.0, 1.1), (3.0, 1.1), (4.0, 1.1), (5.0, 1.1), (1.0, 1.1)]

Where is the error?

Upvotes: 1

Views: 39

Answers (2)

atru
atru

Reputation: 4744

If you want a list comprehension, you need to use one that takes into account that your list d is nested,

g = [[y[:2] for y in x] for x in d]

Here the outer list comprehension loops through the inner lists of d, and the inner list comprehension loops through the tuples in those inner lists.

Upvotes: 1

Eimantas G
Eimantas G

Reputation: 467

This code prints out your desired output:

l = [[(1.0,1.1,1223),(2.0,1.1,1224)],[(3.0,1.1,1222),(4.0,1.1,1222)],[(5.0,1.1,1222),(1.0,1.1,1222)]]

b = []

times = 0

for a in l:
    b.append([])
    for x in range(2):
        b[times].append((a[x][0],a[x][1]))
        
    times += 1        
            
print(b)

Upvotes: 0

Related Questions