i have a big list that consists of multiple lists of arbitrary lengths. I want to compare each list length and create new lists of equal sizes. For example,
biglist = [['x','y','z'],['a','b'],['d','f','g'],...,['r','e','w','q','t','u','i']]
expected_list= [['a','b'],[['x','y','z'],['d','f','g']],....,['r','e','w','q','t','u','i']]
I am new to python. can anyone suggest me a less expensive method to do the above process. Thanks in advance.
It looks like you want to groupby
a list by its element len
s:
>>> biglist = [['x', 'y', 'z'], ['a', 'b'], ['d', 'f', 'g'], ['r', 'e', 'w', 'q', 't', 'u', 'i']]
>>> expected_list = [list(b) for a, b in itertools.groupby(sorted(biglist, key=len), len)]
>>> expected_list
[[['a', 'b']], [['x', 'y', 'z'], ['d', 'f', 'g']], [['r', 'e', 'w', 'q', 't', 'u', 'i']]]
May I suggest using itertools groupby function?
import itertools
biglist = [['x','y','z'],['a','b'],['d','f','g'],['r','e','w','q','t','u','i']]
print(list(list(i[1]) for i in itertools.groupby(sorted(biglist, key=len), len)))
Which outputs
[[['a', 'b']], [['x', 'y', 'z'], ['d', 'f', 'g']], [['r', 'e', 'w', 'q', 't', 'u', 'i']]]
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.