Home > database >  how to sort list of integers and lists in python?
how to sort list of integers and lists in python?

Time:07-21

Like I have this list and I tried many things but end up getting type error. Is it even possible in python?

Input = [3,1,0,4,1,[5,4,7]]

output = [0,1,1,3,4,[4,5,7]]

CodePudding user response:

You can use itertools.groupby:

from itertools import groupby

def sorted_mixed(lst):
    output = []
    for k, g in groupby(lst, key=lambda x: isinstance(x, list)):
        if k: # if the group consists of lists
            output  = [sorted(x) for x in g] # sort each list
        else: # if the group consists of others
            output  = sorted(g)
    return output

print(sorted_mixed([3,1,0,4,1,[5,4,7]]))
# [0, 1, 1, 3, 4, [4, 5, 7]]
print(sorted_mixed([3,1,[9,4,1],4,1,[5,4]]))
# [1, 3, [1, 4, 9], 1, 4, [4, 5]]
print(sorted_mixed([[4,3],[2,1]]))
# [[3, 4], [1, 2]]

CodePudding user response:

The items are sorted locally, not globally. For a different behavior more information should be given.

from itertools import groupby, chain

a = [3,1, [9, 4, 1],4,1,[5,4]]

out = list(chain.from_iterable([sorted(next(grp))] if gr_type == list else sorted(grp) for gr_type, grp in groupby(a, key=type)))
print(out)
#[1, 3, [1, 4, 9], 1, 4, [4, 5]]

CodePudding user response:

Hey Anshuman Sharma there are many ways to solve it, as a beginner in python I solved it like this, but there are more elegant ways with list comprehension.

Input = [3, 1, 0, 4, 1, [5, 4, 7]]
new_list = []
for value in Input:
    if type(value) != list:
        new_list.append(value)
    else:
        for element in value:
            new_list.append(element)

print(f"This is the new list: {new_list}")
new_list.sort()
print(new_list)
  • Related