根据嵌套列表中特定索引处的元素过滤列表 [英] Filter list based on the element in nested list at specific index
本文介绍了根据嵌套列表中特定索引处的元素过滤列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表列表,其中包含:
I have a list of list containing:
[['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
我想通过引用列表列表中每个列表的第三部分中的字母从列表列表中获取值.
and i want to obtain the value from the list of list by referring to the alphabet in the third section of every list inside the list of list.
例如,我希望python为列表列表中的每个项目打印元素以字母'G'表示的.
example, I want python to print the element represented by letter 'G' for every item in the list of list.
output = [4.2,3.4]
[8.7,5.4]
这是我尝试过的:
L = [['4.2','3.4','G'],['2.4','1.2','H'],['8.7','5.4','G']]
newList = []
for line in L:
if line[0][2] == 'G'
newList.append([float(i) for i in line[0:2]])
print(newList)
我的错误将出现在第5行,因为我不确定我是否可以这样做.问候.
my error would be on line 5 as I'm not sure if i am able to do it this way. Regards.
推荐答案
您的代码中有2个问题,
There are 2 issues in your code,
1. line = ['4.2', '3.4', 'G'] for 1st iteration
hence to check for 'G', look out for line[2] == 'G' instead of line[0][3] == 'G'
2. use 'G' instead off 'house'.
>>> for line in L:
... if line[2] == 'G':
... newList.append([float(i) for i in line[0:2]])
...
>>> newList
[[4.2, 3.4], [8.7, 5.4]]
这篇关于根据嵌套列表中特定索引处的元素过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文