Reputation: 153
Given the following list:
labels = [0, 1, 2, 3, 4]
I wish I could obtain the following by using just one line of code:
['0-1', '1-2', '2-3', '3-4', '4-0']
I can do this with 2 lines of code:
pairwise_labels = [f"{i}-{i+1}" for i in range(len(labels)-1)]
pairwise_labels.append(f"{len(labels)-1}-0")
With just one line, my code will be drastically reduced, as I always need to create an if
for the last case to close the loop.
Upvotes: -1
Views: 129
Reputation: 42133
You can leverage Python's ability to use negative indexes:
labels = [0, 1, 2, 3, 4]
pl = [f"{a}-{labels[i]}" for i,a in enumerate(labels,1-len(labels))]
print(pl)
['0-1', '1-2', '2-3', '3-4', '4-0']
Upvotes: 1
Reputation: 120509
You can slice your list:
>>> [f'{i}-{j}' for i, j in zip(labels, labels[1:] + labels[:1])]
['0-1', '1-2', '2-3', '3-4', '4-0']
Upvotes: 2
Reputation: 749
Your one liner:
pairwise_labels = [f'{a}-{b}' for a, b in zip(labels, labels[1:] + [labels[0]])]
Upvotes: 2
Reputation: 37847
One option would be to use pairwise
(New in version 3.10) :
from itertools import pairwise
labels = [0, 1, 2, 3, 4]
pairwise_labels = [f"{x}-{y}" for x, y in pairwise(labels + [labels[0]])]
Output :
print(pairwise_labels)
#['0-1', '1-2', '2-3', '3-4', '4-0']
Upvotes: 4
Reputation: 335
You can do this in one line using modular arithmetic.
pairwise_labels = [f"{labels[i]}-{labels[(i+1)%len(labels)]}" for i in range(len(labels))]
Upvotes: 3