简体   繁体   English

遍历python中每个嵌套列表的第二个值

[英]iterate through second value of each nested list in python

Probably something really simple, but I'm having some real trouble with it. 可能确实很简单,但是我遇到了一些麻烦。 I have a list that's like so: 我有一个像这样的列表:

[[1, 2500],[3,4319],[8,3292],[3,34590]]

where the first value in each nested list is a score of some kind and the second value is the user id that the score corresponds to. 其中每个嵌套列表中的第一个值是某种分数,第二个值是该分数对应的用户ID。

I'm trying to do some simple arithmetic on the list to remove all user IDs in a second list. 我正在尝试对列表执行一些简单的算法,以删除第二个列表中的所有用户ID。 however, I'm finding that I can't address only the second element of each nested list. 但是,我发现我无法仅解决每个嵌套列表的第二个元素。

newlist = list(set(oldlist[][1]) - set(to_be_removed))

am I trying to get too creative with the brackets, or am I just missing something very simple? 我是想在方括号上变得太有创意了,还是只是缺少一些简单的东西?

在这里使用列表理解将是最简单的解决方案:

new_list = [x for x in old_list if x[1] not in to_be_removed]

Something like this? 像这样吗

old_list = [[1, 2500],[3,4319],[8,3292],[3,34590]]
removals = set([2500, 34590])
new_list = [[x, y] for x, y in old_list if y not in removals]

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

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