Good day. There is a list of gen = [1,2,3,4] It is necessary to combine the elements into a number in order to get 1234 . I did this:

 chislo = int(''.join((str(i) for i in gen))) 

Is there no easier way without type conversion?

3 answers 3

To turn a sequence of numbers into a number:

 digits = [1, 2, 3, 4] number = int(''.join(map(str, digits))) # -> 1234 

It is close to the code in question and converts all the numbers into strings, combines them into one string, which is converted to an integer. This is ugly (due to back-to-back conversions: int<->str ), but a faster way for thousands of digits compared to the reduce() solution below.

You can do without type conversions:

 from functools import reduce number = reduce(lambda n, d: 10*n + d, digits) 

where instead of reduce() you can explicitly write a loop:

 number = digits[0] for d in digits[1:]: number = 10 * number + d 

You can see a visualization of intermediate steps, like the number is considered, on pythontutor.com :

 number = 1 number = 10 * 1 + 2 = 12 number = 10 * 12 + 3 = 123 number = 10 * 123 + 4 = 1234 
     gen = [1, 2, 3, 4] x = len(gen) - 1 res = 0 for i, v in enumerate(gen): res += v * 10 ** (x - i) 

    Slightly more beautiful solution:

     gen = [1, 2, 3, 4] sum([value * 10 ** index for index, value in enumerate(gen[::-1])]) 
    • Damn, who said that the array is character) +1 - isnullxbh
    • @slippyk cool :) and fast - dio4
    • @slippyk and as always - a minimum of words and good code. - dio4
    • instead of sum([..]) you can write simply sum(..) without creating an intermediate list: sum(digit * 10**place for place, digit in enumerate(digits[::-1])) - jfs
     s = filter(str.isdigit, repr(gen)) num = int(s) 

    Example

    • do you have a type conversion here? num = int (s) - dio4
    • @ dio4, like that. But in my opinion, this is a better code for your task. But it is in my opinion, as you - ...)) - isnullxbh
    • This is not my task and I liked your answer)) but there is a type conversion there, but the author asks without it;) - dio4
    • @ dio4, will be now. - isnullxbh
    • one
      Two more words .. I like slippyk in all respects. No mentoring in the "voice", no "instructing", narcissism, a minimum of words, and if they correct someone where, then they are not intrusive, not insulting, and correct code, and not empty reasoning. - dio4