按内部列表的一个元素过滤内部列表的列表

时间:2018-04-22 20:09:53

标签: python-3.x

我正在尝试在列表中提取/存储所有值,例如#&39; 55095571 @ NO2'和' 25613911 @ N00'附在'未显示' &安培; '未知'

index  type  size  value

0  list 2     ['Not shown', '55095571@N02']
1  list 2     ['Dublin, Ireland', '87036731@N04']
2  list 2     ['Dublin, Ireland', '87036731@N04']
3  list 2     ['Teddington, UK', '12220922@N05']
4  list 2     ['Peterborough (UK)', '91415433@N03']
5  list 2     ['Dublin, Ireland', '87036731@N04']
6  list 2     ['Unknown', '34305619@N06']
7  list 2     ['Unknown', '99902388@N04']
8  list 2     ['Unknown', '25613911@N00']

任何帮助或建议都会很棒!

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用filter(function, iterable)来过滤可迭代的内容。该函数必须返回True以获取所需的值。如果列表的第一个元素位于您想要的那个元素中,我会传递一个返回True的{​​{3}}函数。

我将您的输出合并到一个列表中以进行操作:

data = [ ['Not shown', '55095571@N02']
       , ['Dublin, Ireland', '87036731@N04']
       , ['Dublin, Ireland', '87036731@N04']
       , ['Teddington, UK', '12220922@N05']
       , ['Peterborough (UK)', '91415433@N03']
       , ['Dublin, Ireland', '87036731@N04']
       , ['Unknown', '34305619@N06']
       , ['Unknown', '99902388@N04']
       , ['Unknown', '25613911@N00']]

# filter all that have the desired 1st param from the data  
codes = list( filter( lambda x: x[0] in ['Not shown','Unknown'],data))

for t,c in codes: 
    print(c)  # just print coords

# extract coords in seperate list
c = [d[1] for d in codes]

# print list
print(c)

输出:

55095571@N02
34305619@N06
99902388@N04
25613911@N00

['55095571@N02', '34305619@N06', '99902388@N04', '25613911@N00']