sorting - python - change element while in for loop -
let's have 3 lists:
lista = [5,6,2] listb = [7,1] listc = [5,3,6]
i sort lists in 1 for
loop, like:
for thislist in [lista, listb, listc]: # edited, 'list' here thislist = thislist.sort()
where thislist
lista
, listb
, listc
, @ end lists this:
lista = [2,5,6] listb = [1,7] listc = [3,5,6]
is there way this?
note - example, problem i'm dealing kinda harder, wanted make simple example of need.
--edit--
what if make custom sorting here? know that, example, can make custom sorting way: mylist = sorted(mylist, key= lambda val: val/2)
but i'm using sorted
, not sort
here.
can use custom sorting in sort
?
asking cause given answers (thx btw ;) ) using sort
...
you're close. want is:
for thislist in [lista, listb, listc]: thislist.sort()
the first problem in code using list
loop variable, thislist
inside loop. aren't same. so, whatever had assigned thislist
earlier in module or interactive session, sorting on , on again, without affecting lista
, listb
, , listc
.
the second problem list.sort
method sorts list in-place , returns none
, don't want return value. it's harmless overwrite thislist
variable none
, it's confusing reader, don't it.
since you've edited question different:
what if make custom sorting here? know that, example, can make custom sorting way: mylist = sorted(mylist, key= lambda val: val/2) … can use custom sorting in sort?
look @ docs sorted
, list.sort
. both of them take key
argument, , both document same way. if can't guess whether work same way, take couple seconds test yourself:
>>> lst = [2, 11] >>> sorted(lst, key=str) [11, 2] >>> lst.sort(key=str) >>> lst [11, 2]
Comments
Post a Comment