Python 从嵌套列表中获取索引位置
我有一个嵌套列表Python 从嵌套列表中获取索引位置,python,list,for-loop,indexing,nested,Python,List,For Loop,Indexing,Nested,我有一个嵌套列表 nested_list = [["cats", "dogs", "cars"], ["dogs", "green", ", "red"], ["cars", "black", "purple"]] 我需要得到嵌套列表范围内的每个索引位置[1] 因此,我得到了结果列表[“猫”、“狗”、“车”]您可以使用列表理解从所需的索引位置构建结果列表 result = [sublist[0] for sublist in nested_list] 顺便说一句,python索引从0开始。一
nested_list = [["cats", "dogs", "cars"], ["dogs", "green", ", "red"], ["cars", "black", "purple"]]
我需要得到嵌套列表范围内的每个索引位置[1]
因此,我得到了结果列表
[“猫”、“狗”、“车”]
您可以使用列表理解从所需的索引位置构建结果列表
result = [sublist[0] for sublist in nested_list]
顺便说一句,python索引从0开始。一种简单的方法是在python中使用列表理解
>>> nested_list = [["cats", "dogs", "cars"], ["dogs", "green", "", "red"], ["cars", "black", "purple"]]
>>> res = [l[0] for l in nested_list]
['cats', 'dogs', 'cars']
顺便说一句,您说您想要得到位置1的每个元素,但是在您的示例中,您得到的是位置0,Python从位置0开始计数您只是想要
嵌套列表[0]
?你选择的确切清单让你很难说出你想要什么。