0

In my list "A" i have got numbers and ' ', so I want to make a list of list named e.g "b", every list should have nine number (if it possible), no matter how much it have ' '. Any idea how to do this?

A = ['1', '3', '4', '5', '7', '8', '9', ' ', '13', '16', '3', ' ', '5', '17']
B = [ ['1', '3, '4', '5', '7', '8', '9', ' ', '13', '16'], ['3', ' ', '5', '17'] ]
  • Why does this sound like my first college programming course? Have you tried iterating through the array and looking for the break? – TGarrett Feb 28 '17 at 20:08

4 Answers4

0

This will help you:

>>> a = ['1', '3', '4', '5', '7', '8', '9', ' ', '13', '16', '3', ' ',        '5', '17']
>>> b=[a[i:i+9] for i in xrange(0,len(a),9)] 
>>> b
[['1', '3', '4', '5', '7', '8', '9', ' ', '13'], ['16', '3', ' ', '5', '17']]
>>> 
Anurag
  • 59
  • 1
  • 1
  • 6
0

This can be done with two nested while loops:

>>> A = ['1', '3', '4', '5', '7', '8', '9', ' ', '13', '16', '3', ' ', '5', '17']
>>> B = []
>>> while A:
...    L = []
...    c = 0
...    while A and c < 9:
...        L.append(A.pop(0))
...        if L[-1].isdigit():
...           c += 1
...    B.append(L) 
... 
>>> B
[['1', '3', '4', '5', '7', '8', '9', ' ', '13', '16'], ['3', ' ', '5', '17']]

The outer one loops while A is not empty and the inner one while A is not empty and the number of digit only strings appended to the current sub-list is less than 9. The counter is only incremented after a string consisting of only digits is found.

Dan D.
  • 73,243
  • 15
  • 104
  • 123
0

It would be worth your time to get deep into list comprehensions

And there is no xrange in Python 3.x or rather range (in 3.x) does exactly what xrange did in Python 2.x.

A = ['1', '3', '4', '5', '7', '8', '9', ' ', '13', '16', '3', ' ', '5', '17']
B = [i for i in A[0:9]]  #is cleaner.

Though I'm not sure exactly what your goal is. Do you want the second list (the remainder list as I'm thinking of it) to be in the same variable? So if you had 28 elements in your list you'd want three lists of 9 and one list of 1?

TJK
  • 55
  • 1
  • 7
0

This is a bit dirty solution but I think you might need to check isdigit part and pop.

def take(lst, n):
    if not lst:
        return ValueError("Empty list, please check the list.")
    items = list(lst)
    new_list = []
    count = 0
    while items:
        item = items.pop(0)
        new_list.append(item)
        if item.isdigit():
            count += 1
        if count >= n:
            yield new_list
            new_list = []
            count = 0
    if new_list:
        yield new_list


A = ['1', '3', '4', '5', '7', '8', '9', ' ', '13', '16', '3', ' ', '5', '17']
B = [ii for ii in take(A, 9)]
#[['1', '3', '4', '5', '7', '8', '9', ' ', '13', '16'], ['3', ' ', '5', '17']]

Check the following:

sangheestyle
  • 1,037
  • 2
  • 16
  • 28