1

I need help, I'm trying to code a comma separated list but the results to be printed in a different way.

Here is my example code:

a = ('name1', 'name2', 'name3')
b = ('url1', 'url2', 'url3')
results = (a, b)
print(results)

This will show:

(('name1', 'name2', 'name3'), ('url1', 'url2', 'url3'))

However, I would like it to show:

name1, url1, name2, url2, name3, url3

Any help appreciated

Thanks

Willem Van Onsem
  • 397,926
  • 29
  • 362
  • 485
  • 1
    `print(', '.join('{}, {}'.format(*z) for z in zip(a, b)))` but do take a look a tutorial or something. And these are `tuple`s btw, not `list`s. – Ma0 Jul 18 '17 at 12:29
  • 1
    You can use my new favroute syntax (but don't): `a = iter(a); print(list((yield next(a)) or x for x in b))` – Chris_Rands Jul 18 '17 at 12:32
  • @Chris_Rands ????? how does this even work? – Ma0 Jul 18 '17 at 12:35
  • @Ev.Kounis https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions – Chris_Rands Jul 18 '17 at 12:37
  • Possible dupe: https://stackoverflow.com/questions/7946798/interleaving-two-lists-in-python – Chris_Rands Jul 18 '17 at 12:41

4 Answers4

3

You can first use zip(..) to generate 2-tuples for each name and url, then we can use a generator or list comprehension to join these together, like:

print(', '.join(y for x in zip(a,b) for y in x))

This generates:

>>> print(', '.join(y for x in zip(a,b) for y in x))
name1, url1, name2, url2, name3, url3

Or a more declarative style:

from itertools import chain

print(', '.join(chain(*zip(a,b))))

EDIT:

If you want to print the url on separate lines, you can use:

for n,u in zip(a,b):
    print(n,u,sep=',')

Or if you want to produce a string first:

print('\n'.join('{}, {}'.format(*t) for t in zip(a,b))
Willem Van Onsem
  • 397,926
  • 29
  • 362
  • 485
1

This should do the trick.

a = ('name1', 'name2', 'name3')
b = ('url1', 'url2', 'url3')

from itertools import chain

ab = tuple(chain.from_iterable(zip(a, b)))

lst = ', '.join(ab)
StuxCrystal
  • 826
  • 10
  • 20
0

There are a plethora of ways to do this, here is what first came to my mind.

import operator
results = reduce(operator.add, zip(a, b))

Here is another more 'broken down' maybe ugly way of doing it, however it's easier to see what's going on.

results = []
while True:
    try:
         results.append(a.pop(0))
         results.append(b.pop(0))
    except IndexError:
        break
PeskyPotato
  • 630
  • 7
  • 19
0

Willem's answer is the way to go for your original question.

If you want to do more than just display the elements, you might want to use a dict for your data:

>>> dict(zip(a,b))
{'name2': 'url2', 'name3': 'url3', 'name1': 'url1'}

If the order is important, you can use an OrderedDict:

>>> from collections import OrderedDict
>>> OrderedDict(zip(a,b))
OrderedDict([('name1', 'url1'), ('name2', 'url2'), ('name3', 'url3')])
Eric Duminil
  • 50,694
  • 8
  • 64
  • 113