英文:
How to get the most duplicates in 2d list
问题
我有一个包含超过20行的二维列表。我想要对每个子列表进行排序并返回其中重复次数最多的元素。例如,以下是我的列表:
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]]
我希望我的结果如下:
List2 = [[b,v,a,x],[c],[h,j,c,f]]
英文:
I have a 2d list with more than more than 20 rows. I would like to sorted and return the most duplicates in each sublist.For example, here is my list 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 my result to be like this.
List2 = [[b,v,a,x],[c],[h,j,c,f]]
答案1
得分: 3
你可以使用 `Counter.most_common` 来按频率顺序获取子列表中的项目。 在这里,`v` 比 `b` 更常见:
```py
from collections import Counter
a="a"; b="b"; c="c"; d="d"; f="f"; h="h"; j="j"; p="p"; v="v"; x="x"
ll = [[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]]
ls = [[e for e, n in Counter(items).most_common() if n >= 2] for items in ll]
print(ls) # [['v', 'b', 'a', 'x'], ['c'], ['h', 'j', 'c', 'f']]
<details>
<summary>英文:</summary>
You can use `Counter.most_common` to get the items in the sublist in order of frequency. `v` is more common than `b` here:
```py
from collections import Counter
a="a"; b="b"; c="c"; d="d"; f="f"; h="h"; j="j"; p="p"; v="v"; x="x"
ll = [[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]]
ls = [[e for e, n in Counter(items).most_common() if n >= 2] for items in ll]
print(ls) # [['v', 'b', 'a', 'x'], ['c'], ['h', 'j', 'c', 'f']]
答案2
得分: 2
这是使用Counter的解决方案的代码:
import collections
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']]
list2 = []
for l in list1:
c = collections.Counter(l)
list2.append([k for k, v in c.items() if v > 1])
print(list2)
输出结果为:
[['a', 'b', 'v', 'x'], ['c'], ['j', 'c', 'f', 'h']]
英文:
Here's the solution using a Counter:
import collections
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"]]
list2 = []
for l in list1:
c = collections.Counter(l)
list2.append( [k for k,v in c.items() if v > 1] )
print(list2)
Output:
[['a', 'b', 'v', 'x'], ['c'], ['j', 'c', 'f', 'h']]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论