I’m trying to figure out how to sort a list but not all at once like in:
list.sort()
But instead I want to sort the first 3, then the next 3 and so on.
Let’s say my list is the following
list = [ F, V, T, O, D, Q, I, P, M]
Id want the out put to look like this:
[F, T, V, D, O, Q, I, M, P]
Does anyone know how I could go about doing this?
CodePudding user response:
You can sort a slice of a list, and use slice assignment to replace it in the original list:
>>> my_list = ['F', 'V', 'T', 'O', 'D', 'Q', 'I', 'P', 'M']
>>> for i in range(len(my_list) // 3):
... my_list[i*3:i*3 3] = sorted(my_list[i*3:i*3 3])
...
>>> my_list
['F', 'T', 'V', 'D', 'O', 'Q', 'I', 'M', 'P']
Another option would be to build a whole new list with sum
and just assign it to my_list
at the end (whether or not this is equivalent depends on whether there are other references to my_list
anywhere):
>>> my_list = ['F', 'V', 'T', 'O', 'D', 'Q', 'I', 'P', 'M']
>>> my_list = sum((sorted(my_list[i*3:i*3 3]) for i in range(len(my_list) // 3)), [])
>>> my_list
['F', 'T', 'V', 'D', 'O', 'Q', 'I', 'M', 'P']
CodePudding user response:
Just for fun a silly hack you shouldn't rely on:
i = iter(range(len(lst)))
lst.sort(key=lambda x: (next(i) // 3, x))
CodePudding user response:
my_list = ["F", "V", "T", "O", "D", "Q", "I", "P", "M"]
slice = 3
sorted_list = sum([sorted(my_list[i:i slice]) for i in range(0, len(my_list), slice)], [])
# ['F', 'T', 'V', 'D', 'O', 'Q', 'I', 'M', 'P']