Python-如何获取python3列表中列表中的第一项 [英] Python - How to get first item in list on list in python3

查看:134
本文介绍了Python-如何获取python3列表中列表中的第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个类似于以下的列表:

I have a list in python like the following:

edge =  [[1, 2], [1, 3], [1, 4], [3, 4]]

我要打印 1 1 1 3 ; aka每个子列表的第一个元素。

I want to print 1 and 1 and 1 and 3; aka the first element of each sub-list.

我使用以下代码:

for subList in edge:
    for firstItem in subList:
        print(firstItem)

但是它会打印所有元素。

But it prints all elements..

推荐答案

您正在遍历所有嵌套列表的所有元素。如果只想打印每个嵌套列表的第一个元素,请使用索引:

You are looping over all elements of all nested lists. If you only wanted to print the first element of each nested list, use indexing:

for sublist in edge:
    print(sublist[0])

如果所有嵌套列表具有相同数量的元素,则可以使用拆包:

If all nested lists have the same number of elements you could use unpacking:

for start, end in edge:
    print(start)

这篇关于Python-如何获取python3列表中列表中的第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆