fac*_*off 5 python list python-3.x
我有一个
list1 = ["one", "two", "two", "three", "four" , "five", "five", "five", "six"]
Run Code Online (Sandbox Code Playgroud)
而输出应该是
list2 = ["five" , "two", "one", "three" , "six"]
Run Code Online (Sandbox Code Playgroud)
"five"
是第一个元素,因为在list1中出现的次数最多(3)"two
"是第二个元素,因为在list1中出现次数最多(2)"one"
,"three
"并且"six"
具有相同较低的出现次数(1),因此它们是我的最后一次list2
- 只要它们在"五"和"两"之后,它们的位置并不重要.简而言之,list2 = ["five" , "two", "six", "three" , "one"]
或者list2 = ["five" , "two", "three", "one" , "six"]
或接受任何其他变化.我可以通过创建一个字典来存储出现次数来解决这个问题,然后用dict命令我的项目创建一个新的列表
my_dict = {i:list1.count(i) for i in list1}
Run Code Online (Sandbox Code Playgroud)
但我需要更清洁的东西
您可以使用列表理解和Counter
:
from collections import Counter
print([element for element,count in Counter(list1).most_common()])
Run Code Online (Sandbox Code Playgroud)
输出:
['five', 'two', 'three', 'six', 'four', 'one']
Run Code Online (Sandbox Code Playgroud)