Making Sub Lists Based on Lengths of Items

75 Views Asked by At

I want to split a list I have of 48 different lengths into a new list for each length of the item. I could do something like

for item in list:
    if len(item) == 1:
         len1list.append(item)
    if len(item) == 2:
         len2list.append(item)

etc etc but that would require 48 if statements, just wondering whether there was a more Pythonic way, using less lines of code.

2

There are 2 best solutions below

2
On BEST ANSWER

You want to categorize your list based on its items length. So you can sort based on length and group them.You can use itertools.groupby for grouping the sub lists (or any iterable object):

>>> l=[[1],[3,4],[5],[6,7,8],[4,0],[2],[5,6,7]]
>>> from itertools import groupby
>>> [list(g) for _,g in groupby(sorted(l,key=len),key=len)]
[[[1], [5], [2]], [[3, 4], [4, 0]], [[6, 7, 8], [5, 6, 7]]]

There is some notes here :

  • If you don' t want to do operations like indexing or other operations on list, you don't need to convert the result to list (as i have done in above answer) you can let the result to be as a generator that is pretty much efficient for long lists.

  • If you want more performance in run time you can use dictionaries that use hash-table for storing their data which searching and inserting data has O(1) in them. @junnytony suggested a good way with defaultdict. you can also use dict.setdefault method :

    d={}
    for i in main_list:
        d.setdefault(len(i),[]).append(i)
    
    print d.values()
    
2
On

You can use a defaultdict of lists. This is a dictionary that is initialized with a list for each key, so you can just append your items of different lengths to the appropriate list using the lengths of items as keys.

from collections import defaultdict
items_by_length = defaultdict(list)

for item in orig_list:
    items_by_length[len(item)].append(item)

grouped_list = list(items_by_length.values())