[英]How to swap the elements in a list if elements are same in python?
I have a issue.我有一个问题。 If I have list say ['a','b','c','a','b','c'].
如果我有列表说['a','b','c','a','b','c']。 How do I place same values next to each other?
如何将相同的值放在一起?
input: l = ['a','b','c','a','b','c']
excepted output: l =['a','a','b','b','c','c']
You can call sorted()
function on your list to get a lexicographically sorted new list:您可以在列表中调用
sorted()
function 以获取按字典顺序排序的新列表:
>>> sorted(['a','b','c','a','b','c'])
['a', 'a', 'b', 'b', 'c', 'c']
Refer sorted()
document for more details.有关详细信息,请参阅
sorted()
文档。
solution using sort is better but if you would like to see another one this also works使用 sort 的解决方案更好,但是如果您想查看另一个解决方案,这也可以
l = ['a','b','c','a','b','c']
ans = []
for x in set(l):
ans.extend([x] * l.count(x))
Two of the possibly many ways:可能的多种方式中的两种:
from collections import Counter
c = Counter(arr)
res = []
for k,v in c.items:
res+=[k]*v
print(*res)
arr.sort()
print(arr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.