虽然其他答案是正确的,但这是另一种方法,无需以简单易懂的方式使用任何外部包 -
lst= ['Red','Green','Yellow','Blue','Blue','Green','Red','Yellow','Purple']
dictionary = {}
# Store the frequency of each element that occurs in list
for i in lst :
if(dictionary.get(i)==None):
dictionary[i]=1
else :
dictionary[i]+=1
ans=[]
# Generate the final answer by making list with each element occurring according to their frequency
for k in dictionary.keys():
tmp = [k]*dictionary[k]
ans.append(tmp)
print(ans)
输出:
[['Red', 'Red'], ['Green', 'Green'], ['Yellow', 'Yellow'], ['Blue', 'Blue'], ['Purple']]
或者,如果你不想生成二维列表,你可以直接打印每个元素的列表,它们分别出现的频率为 -
lst= ['Red','Green','Yellow','Blue','Blue','Green','Red','Yellow','Purple']
dictionary = {}
# Same as in last example... just a more pythonic way of doing it
for i in lst :
dictionary[i]=dictionary.get(i,0)+1
for k in dictionary.keys():
elements = [k]*dictionary[k]
print(elements)
输出:
['Red', 'Red']
['Green', 'Green']
['Yellow', 'Yellow']
['Blue', 'Blue']
['Purple']
您将获得与您在问题中提出的完全相同的输出。如果您愿意在没有任何外部包的情况下完成任务,这将是最好的方法。