简体   繁体   中英

python | Get first elements of 2d list

i have following List:

j = [
    [(1, 100), (2, 80), (3, 40)],
    [(2, 80), (1, 30), (4, 50), (3, 60)],
    [(1, 40), (2, 70), (4, 30)]
]

How can i print every first element like this:

[1, 2 ,3]
[2, 1, 4, 3]
[1, 2, 4]

I tried with

for i in j:
print(i[0])

Thanks!

Using zip and a list comprehension:

[next(zip(*i)) for i in j]

[(1, 2, 3), (2, 1, 4, 3), (1, 2, 4)]

Or using a nested loop:

[[v[0] for v in i] for i in j]

[[1, 2, 3], [2, 1, 4, 3], [1, 2, 4]]

Try this:

for i in j:
    print([v[0] for v in i])

You can use python's list comprehensions for each list i:

for i in j:
    print([x for x,y in i])

If you haven't used list comprehensions before, this means for each item in the list i (in this case a tuple (x,y)), use the value of x for this new list we are creating.

The ugliest, least pythonic form, but easiest to understand:

for i in j:
   l=[]
   for m in i:
      l.append(m[0])
   print(l)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM