首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从2D列表、Python中删除重复元素(而不是列表)

从2D列表、Python中删除重复元素(而不是列表)
EN

Stack Overflow用户
提问于 2022-11-26 16:32:21
回答 3查看 50关注 0票数 2

我想从不止一次出现的列表中删除所有元素,并正在寻找一个比以下更流畅的解决方案:Removing Duplicate Elements from List of Lists in Prolog

我并不试图删除父列表中的重复列表,比如:How to remove duplicates from nested lists

考虑一下这个国际组织:

代码语言:javascript
复制
list = [
[1, 3, 4, 5, 77],
[1, 5, 10, 3, 4],
[1, 5, 100, 3, 4], 
[1, 3, 4, 5, 89], 
[1, 3, 5, 47, 48]]

期望产出:

代码语言:javascript
复制
new_list= [
[77],
[10],
[100], 
[89], 
[47, 48]]

谢谢。我将在Pandas中使用这一点:与原始列相比,new_list将作为一个新列,每一行的值都是唯一的。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-11-26 17:09:35

也许有更时髦的方法,但这是可行的:

代码语言:javascript
复制
from collections import Counter

mylist = [
[1, 3, 4, 5, 77],
[1, 5, 10, 3, 4],
[1, 5, 100, 3, 4], 
[1, 3, 4, 5, 89], 
[1, 3, 5, 47, 48]]


flat = [y for x in mylist for y in x]    
count = Counter(flat)
uniq = [x for x,y in count.items() if y == 1]
new_list = [[x for x in y if x in  uniq] for y in mylist]

这给

代码语言:javascript
复制
[[77], [10], [100], [89], [47, 48]]
票数 2
EN

Stack Overflow用户

发布于 2022-11-26 17:31:38

代码语言:javascript
复制
for bi,lst in enumerate(l):
    for el in lst:
        for i in range(len(l)):
            if bi != i:
                if el in l[i]:
                    print(f'element:{el}')
                    print(f'passing over list:{l[i]}')
                    l[i].remove(el)
                    try: l[bi].remove(el)
                    except: continue

这个方法并没有那么有用,但我发现通常其他的答案(包括链接的帖子)会使用另一个模块,所以我尝试了不同的方法。

票数 1
EN

Stack Overflow用户

发布于 2022-11-28 07:56:53

我的解决方案:将多次出现的元素列表(一旦有)与原始的2D列表进行比较:

代码语言:javascript
复制
list1 = [1,3,4,5]

for  list_of_numbers  in numbers:
        for number in list_of_numbers:
            while number in list_of_numbers and list1:
                      list_of_numbers.remove(number)
            


[[77], [10], [100], [89], [47, 48]]

有人能用迭代来表达同样的信息吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74583876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档