heather heather - 2 months ago 6x
Python Question

Sublist to number

I'm working on the solution to a fun problem I found. The code I have gives a bunch of sublists, like (1, 2, 3, 0, 0). Is there a way to turn that sublist into the number 12300 and append it to a new list,

? I would have to do this for quite a few sublists, so preferably it would be a function I could run on the whole list (i.e., it'd iterate through the list, do the conversion for each number, and append each new number to the new list, though the old list would stay exactly the same).

So far, I have the code

import itertools
digits = [1,2,3,0,0]
perm = list(itertools.permutations(digits))
perm2 = []

print perm
def lst_var (lst):
for i in lst:
litem = lst[i]
#conversion takes place


But I really don't know how to do the conversion, and I can't find a solution anywhere. Any help would be appreciated.


pzp pzp

Here is a function that creates an integer out of a list of numbers. The advantage of this function is that it does not convert the list of integers into a list of strings, which is a rather costly operation:

def list_to_int(ls):
    num = 0
    for digit in ls:
        num += digit
        num *= 10
    return num / 10

Applied to your example:



In order to apply it to a list of sublists, you can either use a list comprehension or, as I would personally prefer, map:

sublists = [[7, 6, 6], [5, 7, 6], [9, 0, 9, 0], [8, 9, 5, 7, 8, 4]]
map(list_to_int, sublists)

[766, 576, 9090, 895784]

So, following that model your code would end up looking something like:

digits = [1,2,3,0,0]
perm = map(list_to_int, itertools.permutations(digits))