Sam
Sam

Reputation: 1

Python, list of lists with sorted numbers by 4 first digits

I have a list which contains numbers and I want to create a new list which contains separate lists of all numbers with the same 4 first digits.

Example: make l2 from l1

l1 = [100023,100069,222236,22258,41415258,41413265,1214568...]

l2 = [[100023,100069],[222236,22258],[41415258,41413265],[1214568]...]

how can I create l2 from l1?

I tried iterating over the elements of l1 but w/o success!!

def main():

    l1=[100023,100069,222236,22258,41415258,41413265,1214568]
    l2=[[100023,100069],[222236,22258],[41415258,41413265],[1214568]]
    x=0
    n=1
    for i in l2:
        if i[0:4] == l2[n][0:4]:
            l2[x].append(i)
        else:
            l2[x+1].append(i)
    print(l2)

if __name__ == '__main__':
    main()

Still not know how to proceed..

Upvotes: 0

Views: 45

Answers (2)

Florian Weimer
Florian Weimer

Reputation: 33727

You could use itertools.groupby after converting the list elements to strings and using the first for digits as keys:

import itertools
l2 = [list(value) for key, value
      in itertools.groupby(l1, lambda x: str(x)[:4])]
print(l2)

EDIT: Frieder's solution is pretty much how this is implemented behind the scenes.

Upvotes: 1

Frieder
Frieder

Reputation: 1266

You could create a dict as intermediate result and then convert this dict back to a list. You also need to convert your integers to strings first.

l1 = [100023,100069,222236,22258,41415258,41413265,1214568]
l2 = []
l2dict = {}
for i in l1:
    prefix = str(i)[0:4]
    if prefix in l2dict.keys():
        l2dict[prefix].append(i)
    else:
        l2dict[prefix] = [i]
for item in l2dict.values():
    l2.append(item)
print(l2)

Upvotes: 2

Related Questions