Reputation: 115
I would like to take a var containing numbers and create a list of 2 digit numbers.
For instance:
x = 123456
I want to create a list of 2 digit chunks
y = [12,34,56]
I can't seem to figure this one out.
Upvotes: 0
Views: 171
Reputation: 206
If x
is string:
x = '1234563'
a = [x[i * 2 : (i + 1) * 2] for i in range(len(x) // 2)]
If x
is int:
x = 1234563
l = len(str(x))
a = [(x // (10 ** (i - 2))) % 100 for i in range(l, 2, -2)]
Upvotes: 0
Reputation: 41
def trunk(numbers, chunkSize):
new_list = []
nums = str(numbers)
for x in xrange(0, len(nums), chunkSize):
new_list.append(int(nums[x:chunkSize+x]))
return new_list
>>> x = 123456
>>> trunk(x, 2)
[12, 34, 56]
>>> x = 12345
>>> trunk(x, 2)
[12, 34, 5]
Upvotes: 0
Reputation: 22571
>>> x = 123456
>>> [int(str(x)[i:i+2]) for i in range(0, len((str(x)), 2)]
[12, 34, 56]
Upvotes: 0
Reputation: 32439
Use modulo and floor division.
def chunks(n):
if n < 0: raise Exception ("Don't")
while n:
yield n % 100
n //= 100
a = [c for c in chunks (123456)][::-1]
print(a)
Also PS: For input 12345
the output is [1, 23, 45]
.
And PPS: Is this for FFT multiplication?
Upvotes: 3