如何用一行代码创建一个循环列表?

huangapple go评论57阅读模式
英文:

How to create a circular list in one line of code?

问题

给定以下列表:

labels = [0, 1, 2, 3, 4]

我希望只用一行代码就能得到以下结果:

pairwise_labels = ['0-1', '1-2', '2-3', '3-4', '4-0']

我可以用两行代码实现这个目标:

pairwise_labels = [f"{i}-{i+1}" for i in range(len(labels)-1)]
pairwise_labels.append(f"{len(labels)-1}-0")

只用一行,我的代码就会大幅减少,因为我总是需要为最后一种情况创建一个if来闭合循环。

英文:

Given the following list:

labels = [0, 1, 2, 3, 4]

I wish I could obtain the following by using just one line of code:

pairwise_labels = ['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.

答案1

得分: 4

一种选择是使用 pairwise (自版本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]])]

输出:

print(pairwise_labels)

#['0-1', '1-2', '2-3', '3-4', '4-0']
英文:

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']

答案2

得分: 3

你可以使用模运算在一行内完成此操作。

pairwise_labels = [f"{labels[i]}-{labels[(i+1)%len(labels)]}" for i in range(len(labels))]

英文:

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))]

答案3

得分: 2

pairwise_labels = [f'{a}-{b}' for a, b in zip(labels, labels[1:] + [labels[0]])]

英文:

Your one liner:

pairwise_labels = [f'{a}-{b}' for a, b in zip(labels, labels[1:] + [labels[0]])]

答案4

得分: 2

你可以对列表进行切片:

>>> [f'{i}-{j}' for i, j in zip(labels, labels[1:] + labels[:1])]

['0-1', '1-2', '2-3', '3-4', '4-0']
英文:

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']

答案5

得分: 1

你可以利用Python的负数索引能力:

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']
英文:

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']

huangapple
  • 本文由 发表于 2023年4月17日 02:50:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定