[英]I want to check for a specific element in a sublist and remove repeated sublists with the same element in python
i have this 我有这个
lst = [['100','LA'],['101','NY'],['100','NC']]
lst2 = []
i need to check if there's any 100,101,etc repeated and remove the repeated numbers. 我需要检查是否有任何100,101等重复并删除重复的数字。 So the second list would look like this
所以第二个列表看起来像这样
lst2=[['100','LA'],['101','NY']]
because the 100 was already added once in that second list 因为100已经在第二个列表中添加了一次
A quick and dirty way to do this is using a generic uniqueness filter: 快速而肮脏的方法是使用通用唯一性过滤器:
def uniqueness(iterable,key=lambda x:x):
seen = set()
for item in iterable:
fitem = key(item)
if fitem not in seen:
yield item
seen.add(fitem)
You can then use it like: 然后你可以使用它:
list2 = list(uniqueness(lst,key=lambda x:x[0]))
If you do not specify, the filter will assume the entire element (but this will fail here, because list
is not hashable). 如果未指定,则过滤器将采用整个元素(但这将在此处失败,因为
list
不可清除)。
An answer without lambda's. 没有lambda的答案。
nmbrs = [n for n, city in lst]
lst2 = [x for i, x in enumerate(lst) if x[0] not in nmbrs[:i]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.