给出list = ["one", "two", "three"],我想打印当前及其下一个元素,但顺序相反.即:

three one
two three
one two

我的脚本打印当前元素和下一个元素,但不是以相反的顺序打印:

# It prints:
# one two
# two three
for curr, nxt in zip(list, list[1:]):
    print(curr, nxt)
  • 我如何编辑我的脚本以实现我的目标?

我try 了以下几种方法:

# It prints:
# three one
for curr, nxt in zip(list[-1:], list):
   print(curr, nxt)

但它只给了我一个结果.

推荐答案

我在这里不会 Select 使用Pythonzip作为解决方案,因为需要连接两个数组才能得到循环移位的数组(单独的Slice不能循环移位).但是,我要做的只是遍历反转列表中的所有元素,并通过它的索引获得下一个值,如下所示:

list = ["one", "two", "three"]

for i, curr in enumerate(list[::-1]): # enumerate gives you a generator of (index, value)
   nxt = list[-i] # list[-i-1] would be the current value, so -i would be the next one
   print(curr, nxt)

Edit: 使用list[::-1]比您通常想要的要稍微慢一些,因为它会遍历列表一次来反转它,然后另一次迭代它.更好的解决方案是:

list = ["one", "two", "three"]

for i in range(len(list)-1, -1, -1):
    curr = list[i]
    nxt = list[len(list) - i - 1] # list[i+1] would not work as it would be index out of range, but this way it overflows to the negative side, which python allows.
    print(curr, nxt)

但是,如果您希望使用zip,则需要执行以下操作:

list = ["one", "two", "three"]

for curr, nxt in zip(list[::-1], [list[0]] + list[:0:-1]):
    print(curr, nxt)

您还应该注意到,将变量命名为list并不是一个好主意,因为这样会影响到python的内置list方法,您可能应该将其命名为lst或类似的名称.

Python相关问答推荐

使用FASTCGI在IIS上运行Django频道

韦尔福德方差与Numpy方差不同

如何检测背景有噪的图像中的正方形

Python中的嵌套Ruby哈希

将两只Pandas rame乘以指数

按顺序合并2个词典列表

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

如何杀死一个进程,我的Python可执行文件以sudo启动?

手动设置seborn/matplotlib散点图连续变量图例中显示的值

具有相同图例 colored颜色 和标签的堆叠子图

OpenGL仅渲染第二个三角形,第一个三角形不可见

Discord.py -

如果有2个或3个,则从pandas列中删除空格

jsonschema日期格式

获取PANDA GROUP BY转换中的组的名称

对于标准的原始类型注释,从键入`和`从www.example.com `?

BeatuifulSoup从欧洲志愿者服务中获取数据和解析:一个从EU-Site收集机会的小铲子

时长超过24小时如何从Excel导入时长数据

在一个数据帧中,我如何才能发现每个行号是否出现在一列列表中?

将数据从一个单元格保存到Jupyter笔记本中的下一个单元格