如何移除列表中子列表中的重复项

huangapple go评论87阅读模式
英文:

How to remove duplicate items in sub-lists of a list

问题

  1. [['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,

  1. list1 = [['a', 'a', 'b', 'b', 'b', 'v', 'v', 'v', 'v', 'x', 'x', 'p'],
  2. ['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:

  1. Output = [['a', 'b', 'v', 'x', 'p'], ['b', 'c', 'd'], ['a', 'j', 'c', 'f', 'h']]

答案1

得分: 1

"Counter" 可以在不改变其余顺序的情况下帮助。

  1. from collections import Counter
  2. list(map(list, map(Counter, list1)))
  1. [['a', 'b', 'v', 'x', 'p'], ['b', 'c', 'd'], ['a', 'j', 'c', 'f', 'h']]
英文:

Counter can help without changing the remaining order.

  1. from collections import Counter
  2. list(map(list,map(Counter, list1)))
  1. [['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...,你可以这样写

  1. [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

  1. [list(set(i)) for i in list1]

huangapple
  • 本文由 发表于 2023年5月22日 11:18:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定