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:
from collections import Counter
c = Counter(arr)
res = []
for k,v in c.items:
res+=[k]*v
print(*res)
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.