我想从不止一次出现的列表中删除所有元素,并正在寻找一个比以下更流畅的解决方案:Removing Duplicate Elements from List of Lists in Prolog
我并不试图删除父列表中的重复列表,比如:How to remove duplicates from nested lists
考虑一下这个国际组织:
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]]期望产出:
new_list= [
[77],
[10],
[100],
[89],
[47, 48]]谢谢。我将在Pandas中使用这一点:与原始列相比,new_list将作为一个新列,每一行的值都是唯一的。
发布于 2022-11-26 17:09:35
也许有更时髦的方法,但这是可行的:
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]这给
[[77], [10], [100], [89], [47, 48]]发布于 2022-11-26 17:31:38
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这个方法并没有那么有用,但我发现通常其他的答案(包括链接的帖子)会使用另一个模块,所以我尝试了不同的方法。
发布于 2022-11-28 07:56:53
我的解决方案:将多次出现的元素列表(一旦有)与原始的2D列表进行比较:
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]]有人能用迭代来表达同样的信息吗?
https://stackoverflow.com/questions/74583876
复制相似问题