如何从两端迭代一个序列? [英] How to iterate a sequence from both ends?

查看:56
本文介绍了如何从两端迭代一个序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从两端"(在这里到中间(那部分))迭代(一部分)Python序列.
在C/C ++/Java中,我可以尝试

I want to iterate (part of) a Python sequence "from both ends" (to the middle (of that part), here).
In C/C++/Java, I might try

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

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

I can't seem to decide which of the following variants I dislike best:

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

是否有一种令人愉悦/理智/惯用的方式来处理此问题?

Is there a pleasing/sane/idiomatic way to handle this?

推荐答案

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

Why not zip the list with the reverse of itself?

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

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

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

zip automatically handles lists of different lengths, just make sure you set the midpoint properly (it depends on whether the list is evenly sized or not).

这篇关于如何从两端迭代一个序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆