1

I have this function that can append the first three columns of data to a new empty list. Example output is:

['red', 'blue', 'green', 'yellow', 'purple', 'black']

I would like to enclose every two elements of this list in its own list i.e.

[['red', 'blue'], ['green', 'yellow'], ['purple', 'black']]

How can I do this? Thanks.

def selection_table(table):
    atts = [1,2,3]
    new_table = []
    for row in table:
        for i in range(len(new_atts)):
            new_table.append(row[atts[i]])
    return new_table
dazedconfused
  • 1,312
  • 2
  • 19
  • 26

3 Answers3

2

You can do as in this question:

a = ['red', 'blue', 'green', 'yellow', 'purple', 'black']

def chunks(l, n):
    """ Yield successive n-sized chunks from l.
    """
    for i in range(0, len(l), n):
        yield l[i:i+n]

print(list(chunks(a, 2)))    

Gives:

[['red', 'blue'], ['green', 'yellow'], ['purple', 'black']]
Community
  • 1
  • 1
Marcin
  • 215,873
  • 14
  • 235
  • 294
1
>>> my_list = ['red', 'blue', 'green', 'yellow', 'purple', 'black']
>>> result = (my_list[i:i+2] for i in range(0, len(my_list), 2))
>>> list(result)
[['red', 'blue'], ['green', 'yellow'], ['purple', 'black']]
Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43
0

simple way is use zip :)

test=['red', 'blue', 'green', 'yellow', 'purple', 'black']
c=zip(test[0::2],test[1::2])
map(lambda x :list(x),c)
>>>>[['red', 'blue'], ['green', 'yellow'], ['purple', 'black']]

OR

test=['red', 'blue', 'green', 'yellow', 'purple', 'black']
map(lambda x :list(x),zip(test[0::2],test[1::2]))
Avinash Garg
  • 1,374
  • 14
  • 18