英文:
How to remove duplicate items in sub-lists of a list
问题
[['a', 'b', 'v', 'x', 'p'], ['b', 'c', 'd'], ['a', 'j', 'c', 'f', 'h']]
英文:
I have a 2d list with more than 20 rows but Im having a bit of trouble trying to figure out how to remove duplicates from each sublist in a list without changing the remaining order of unique items in each sub list. Example below,
list1 = [['a', 'a', 'b', 'b', 'b', 'v', 'v', 'v', 'v', 'x', 'x', 'p'],
['b', 'c', 'd', 'c'], ['a', 'j', 'j', 'j', 'c', 'c', 'f', 'f', 'h', 'h', 'h', 'h']]
I would like the output to be like this:
Output = [['a', 'b', 'v', 'x', 'p'], ['b', 'c', 'd'], ['a', 'j', 'c', 'f', 'h']]
答案1
得分: 1
"Counter" 可以在不改变其余顺序的情况下帮助。
from collections import Counter
list(map(list, map(Counter, list1)))
[['a', 'b', 'v', 'x', 'p'], ['b', 'c', 'd'], ['a', 'j', 'c', 'f', 'h']]
英文:
Counter
can help without changing the remaining order.
from collections import Counter
list(map(list,map(Counter, list1)))
[['a', 'b', 'v', 'x', 'p'], ['b', 'c', 'd'], ['a', 'j', 'c', 'f', 'h']]
答案2
得分: 1
set()
可以帮助。
output = [list(set(l)) for l in list1]
英文:
set()
can help.
output = [list(set(l)) for l in list1]
答案3
得分: 0
以下是要翻译的内容:
每个元素的类型是什么?如果它是一个不可变的数据类型,比如int、str、tuple...,你可以这样写
[list(set(i)) for i in list1]
英文:
What is the type of each element? If it is an immutable data type like a int, str, tuple.. you can write like this
[list(set(i)) for i in list1]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论