Home > database >  Rearranging similar elements in a python list
Rearranging similar elements in a python list

Time:12-28

Considering a list

l = ['1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '0', '2', '4', '6', '8', '2', '4', '6', '8', '0', '2', '4', '6']

what could be the logic to rearrange this list into :-

l = ['1', '1', '1', '3', '3', '3', '5', '5', '5', '7', '7', '7', '9', '9', '9', '0', '2', '2', '2', '4', '4', '4', '6', '6', '6', '8', '8', '8']

CodePudding user response:

First, you need to create list of unique items. Than you need repeat each item as many as it count in original list

l = ['1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '0', '2', '4', '6', '8', '2', '4', '6', '8', '0', '2', '4', '6']

unique_l = []
for item in l:
    if item not in unique_l:
        unique_l.append(item)

rearranged_l = []
for item in unique_l:
    rearranged_l  = [item] * l.count(item)

print(rearranged_l)
> ['1', '1', '1', '3', '3', '3', '5', '5', '5', '7', '7', '7', '9', '9', '9', '0', '0', '2', '2', '2', '4', '4', '4', '6', '6', '6', '8', '8']

CodePudding user response:

If you just wanted to sort list then using the .sort() method will do it for you.

Example use :

>>> l = ['1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '0', '2', '4', '6', '8', '2', '4', '6', '8', '0', '2', '4', '6']
>>> l
['1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '0', '2', '4', '6', '8', '2', '4', '6', '8', '0', '2', '4', '6']
>>> l.sort()
>>> l
['0', '0', '1', '1', '1', '2', '2', '2', '3', '3', '3', '4', '4', '4', '5', '5', '5', '6', '6', '6', '7', '7', '7', '8', '8', '9', '9', '9']
>>> l.sort(reverse=True)
>>> l
['9', '9', '9', '8', '8', '7', '7', '7', '6', '6', '6', '5', '5', '5', '4', '4', '4', '3', '3', '3', '2', '2', '2', '1', '1', '1', '0', '0']
>>>

This matches what you're trying to do (group similar elements together)

CodePudding user response:

If you sort the list, it will be arranged in order, like so...

>>> l = ['1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '0', '2', '4', '6', '8', '2', '4', '6', '8', '0', '2', '4', '6']
>>> l.sort()
>>> print(l)
['0', '0', '1', '1', '1', '2', '2', '2', '3', '3', '3', '4', '4', '4', '5', '5', '5', '6', '6', '6', '7', '7', '7', '8', '8', '9', '9', '9']

CodePudding user response:

This works:

l = ['1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '1', '3', '5', '7', '9', '0', '2', '4', '6', '8', '2', '4', '6', '8', '0', '2', '4', '6']
l_even = list()
l_odd = list()
for n in l:
    if int(n) % 2 == 0:
        l_even.append(n)
    else:
        l_odd.append(n)

l_even.sort()
l_odd.sort()
l_out = l_odd   l_even
print(l_out)
  • Related