简体   繁体   English

蟒蛇| 获取二维列表的第一个元素

[英]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:使用zip和列表理解:

[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:您可以对每个列表 i 使用 python 的列表推导式:

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.如果您之前没有使用过列表推导式,这意味着对于列表 i 中的每个项目(在本例中为元组 (x,y)),对我们正在创建的这个新列表使用 x 的值。

The ugliest, least pythonic form, but easiest to understand:最丑陋、最不pythonic 的形式,但最容易理解:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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