Home > Software engineering >  How to join adjacent elements in a list with a string in between?
How to join adjacent elements in a list with a string in between?

Time:02-11

I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Given a list with an even number of integers, join adjacent elements using '-' and print each pair. So it will be that this is given:

a = [1, 2, 3, 4, 5, 6, 7, 8]

and the output needs to be:

1-2
3-4
5-6
7-8

Now I have gotten as far as this, but have no idea what to do next:

a = [1, 2, 3, 4, 5, 6, 7, 8]
a1 = a[::2]
a2 = a[1::2]

duos = zip(a1, a2)
print(list(duos))

And this only gives me this as result:

[(1, 2), (3, 4), (5, 6), (7, 8)]

I feel like I am close and just missing one tiny step.

CodePudding user response:

Build a lazy iterator:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> it = iter(a)
>>> print([f"{x}-{y}" for x,y in zip(it,it)])
['1-2', '3-4', '5-6', '7-8']

CodePudding user response:

Yep, very close indeed.

You can use a generator expression to form the pair strings without the intermediate variables, then "\n".join to make a single string out of the formatted pairs.

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> print("\n".join(f"{a}-{b}" for (a, b) in zip(numbers[::2], numbers[1::2])))
1-2
3-4
5-6
7-8

The more procedural version (that's functionally equivalent, but doesn't form a list, but just prints each pair) would be

for (a, b) in zip(numbers[::2], numbers[1::2]):
    print(f"{a}-{b}")

CodePudding user response:

Completing your work:

for x, y in duos:
    print(f'{x}-{y}')

(Note you need to do this instead of your print(list(duos)), otherwise that consumes the zip iterator and there's nothing left.)

CodePudding user response:

A somewhat fun alternative, easily adapts to similar cases just by altering the string of ends:

from itertools import cycle

a = [1, 2, 3, 4, 5, 6, 7, 8]

for x, end in zip(a, cycle('-\n')):
    print(x, end=end)

For example with cycle(' -*\n'), it would instead print this:

1 2-3*4
5 6-7*8

CodePudding user response:

You're indeed very close. Now just print each pair in duos on a separate line with a dash as separator:

for a,b in duos: print(a,b,sep="-") 

Or you could do it all in one line using a combination of map, zip and join:

print(*map("-".join,zip(*[map(str,a)]*2)),sep="\n")

CodePudding user response:

this should work

>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> it = iter(a)
>>> print([f"{x}-{y}" for x,y in zip(it,it)])
['1-2', '3-4', '5-6', '7-8']
  • Related