0

I've got a list with (for example) 100 entries of the sort ['A0', 'B0', 'A1', 'B1', 'A2', 'B2', ... 'A99', 'B99'].

I'd now like to make this into a list of 50 entries with each entry a tuple (Ai, Bi) such that they are grouped together. So the result should be

[('A0','B0'),('A1','B1'),('A2','B2'),...,('A99','B99')]. Is there a shortcut to achieve this or do I have to use a loop like

for i in numpy.arange(0,100,2):
    newlist.add((oldlist[i], oldlist[i+1]))

I'm trying to do quick and advanced programming in python so I'd prefer using shortcuts, list comprehension, ... and not simple for loops where possible

Wouter Vandenputte
  • 1,948
  • 4
  • 26
  • 50

4 Answers4

3

This is the most pythonic way I can think of:

list(zip(oldlist[::2], oldlist[1::2]))
Djib2011
  • 6,874
  • 5
  • 36
  • 41
1

The code below should simply it:

list_1 = ['A0', 'B0', 'A1', 'B1', 'A2', 'B2']
list_of_groups = [x for x in zip(*(iter(list_1),) * 2)]
jammin0921
  • 242
  • 1
  • 7
1

If you really want, you can do this:

a = ['A0', 'B0', 'A1', 'B1', 'A2', 'B2']
list(zip(*[iter(a)]*2))
# [('A0', 'B0'), ('A1', 'B1'), ('A2', 'B2')]
Chrispresso
  • 3,660
  • 2
  • 19
  • 31
1

Another way wiith numpy

list(map(tuple, np.array(l).reshape(-1, 2)))
#[('A0', 'B0'), ('A1', 'B1'), ('A2', 'B2')]
ansev
  • 30,322
  • 5
  • 17
  • 31