0

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
MacR6
  • 115
  • 4

4 Answers4

3

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?

Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
  • Probably should add an explanatory note that `chunks` yields in reverse order, necessitating the reversing slice (`[::-1]`). Also, it might be clearer to do `reversed([c for c in chunks (123456)])`. – Steven Rumbalski Jan 02 '14 at 19:54
  • @StevenRumbalski Very correct. The main point was to avoid costly string operations. The only possible application of splitting a number into its coefficients of a given base I see is FFT, and then hopefully the order doesn't matter as long as you stick to one and the same. – Hyperboreus Jan 02 '14 at 20:00
  • Thanks, this works for a string but how bout an int? – MacR6 Jan 02 '14 at 20:41
  • 1
    @user2270470 This doesn't work for a string... It takes an `int` (in my example `123456`). – Hyperboreus Jan 02 '14 at 20:42
0

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)]
kostbash
  • 206
  • 3
  • 7
0
>>> x = 123456
>>> [int(str(x)[i:i+2]) for i in range(0, len((str(x)), 2)]
[12, 34, 56]
ndpu
  • 22,225
  • 6
  • 54
  • 69
0
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]
Toni V
  • 41
  • 2