简体   繁体   中英

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']. 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(['a','b','c','a','b','c'])
['a', 'a', 'b', 'b', 'c', 'c']

Refer sorted() document for more details.

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

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)
arr.sort()
print(arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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