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?
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?
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])]) 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) Source: https://ru.stackoverflow.com/questions/603463/
All Articles