简体   繁体   English

如果 python 中的元素相同,如何交换列表中的元素?

[英]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()文档

You can use sort()您可以使用排序()

l = ['a','b','c','a','b','c']
l.sort()
print(l)
# ['a', 'a', 'b', 'b', 'c', 'c']

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:可能的多种方式中的两种:

  1. Use Counter (Linear Time Complexity, Linear Space Complexity)使用计数器(线性时间复杂度、线性空间复杂度)
from collections import Counter
c = Counter(arr)
res = []
for k,v in c.items:
    res+=[k]*v
print(*res)
  1. Use Sort (O(nlogn) Time Complexity, O(1) Space Complexity)使用排序(O(nlogn) 时间复杂度,O(1) 空间复杂度)
arr.sort()
print(arr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM