简体   繁体   English

我想检查子列表中的特定元素,并删除python中具有相同元素的重复子列表

[英]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.

相关问题 如果此子列表中包含特定元素,Python将删除列表中的子列表 - Python remove sublist in a list if specific element inside this sublist 如果在所有子列表中的特定位置找不到某个元素,如何删除子列表? - How do you remove a sublist if a certain element is not found at a specific position across all sublists? 如何创建一个包含最后一个元素的子列表,但对相同大小的所有其他子列表使用通用公式? - How do I create a sublist that contains the last element, but uses a general formula for all other sublists of the same size? 在嵌套列表中的所有子列表中查找子列表中相同的元素索引 - Find index of element in sublist that is same across all the sublists in a nested list Python:访问特定的子列表元素 - Python: Accessing specific sublist element Python:如何在不知道子列表数目的情况下遍历每个子列表的第一个元素? - Python: how do i iterate over the first element of each sublist without knowing the number of sublists? 从每个子列表中删除特定位置的元素 - Remove an element at a specific position from every sublist 将相同的元素附加到python中的几个子列表 - append the same element to several sublists in python Python:避免子列表指向同一元素 - Python: avoid sublists pointing to the same element 从某个元素中删除子列表(python) - remove sublist from certain element (python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM