gpt4 book ai didi

python - 如何从两端迭代一个序列?

转载 作者:行者123 更新时间:2023-11-28 19:47:14 24 4
gpt4 key购买 nike

我想“从两端”(到(那部分的)中间)迭代(部分)Python 序列。
在 C/C++/Java 中,我可能会尝试

int start = 2, beyond = 7;
for (int forward = start, back = beyond ; forward <= --back ; forward++)
printf("%d %d\n", forward, back);

我似乎无法决定我最不喜欢以下哪个变体:

seq = tuple(chr(c) for c in range(ord('a'), ord('z')+1))
start, beyond = 2, 7

print("subtract")
for forward in range(start, beyond):
back = start + beyond - 1 - forward
if (back < forward):
break
print(seq[forward], seq[back])
# if (back <= forward): XXX ERROR, as YvesgereY pointed out
# break
print("reversed")
for forward, back in zip(range(start, beyond),
reversed(range(start, beyond))):
if (back < forward):
break
print(seq[forward], seq[back])
print("step -1")
for forward, back in zip(range(start, beyond), range(beyond-1, start-1, -1)):
if (back < forward):
break
print(seq[forward], seq[back])
print("naked code")
forward, back = start, beyond-1 # thanks again, YvesgereY
while (forward <= back):
print(seq[forward], seq[back])
forward += 1
back -= 1

有没有一种令人愉快/理智/惯用的方式来处理这个问题?

最佳答案

为什么不用 zip 列表本身的反面?

mid = (len(lst) + 1) // 2   
for x, y in zip(lst[:mid], lst[::-1]):
print((x, y))

(1, 5)
(2, 4)
(3, 3)

zip 自动处理不同长度的列表,只需确保正确设置中点(这取决于列表大小是否均匀)。

关于python - 如何从两端迭代一个序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46064448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com