代码之家  ›  专栏  ›  技术社区  ›  d-cubed Tyler Rinker

以元组形式高效地列出从末尾开始的项

  •  3
  • d-cubed Tyler Rinker  · 技术社区  · 16 年前

    我想在Python中列出元组中的项目,从后面开始,转到前面。 类似:

    foo_t = tuple(int(f) for f in foo)
    print foo, foo_t[len(foo_t)-1] ...
    

    我相信这应该不需要尝试就可以…-4,除了…-3。

    2 回复  |  直到 10 年前
        1
  •  6
  •   Alex Martelli    16 年前

    你可以 print tuple(reversed(foo_t)) list 代替 tuple ,或

    print ' '.join(str(x) for x in reversed(foo_t))
    

    还有很多变种。你也可以用 foo_t[::-1] 但我认为 reversed

        2
  •  2
  •   Daniel Stutzbach Edward Leno    16 年前

    首先,一般提示:在Python中,您不需要编写 foo_t[len(foo_t)-1] . 你可以直接写 foo_t[-1]

    要回答您的问题,您可以:

    for foo in reversed(foo_t):
        print foo, # Omits the newline
    print          # All done, now print the newline
    

    或:

    print ' '.join(map(str, reversed(foo_t))
    

    print(*reversed(foo_t))