heather - 1 year ago 95

Python Question

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,

`perm2`

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

perm2.append(v)

lst_var(perm)

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

Thanks!

Answer Source

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:

```
list_to_int([1,2,3,0,0])
```

12300

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))
```