开发者

efficiently list items in tuples starting at end

开发者 https://www.devze.com 2022-12-27 01:02 出处:网络
I\'d like to list the items in a tuple in Python starting with the back and go to front. Simila开发者_开发知识库r to:

I'd like to list the items in a tuple in Python starting with the back and go to front. Simila开发者_开发知识库r to:

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

I believe this should be possible without Try ...-4, except ...-3. Thoughts? suggestions?


You can print tuple(reversed(foo_t)), or use list in lieu of tuple, or

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

and many variants. You could also use foo_t[::-1], but I think the reversed builtin is more readable.


First, a general tip: in Python you never need to write foo_t[len(foo_t)-1]. You can just write foo_t[-1] and Python will do the right thing.

To answer your question, you could do:

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

or:

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

In Python 3, it's as easy as:

print(*reversed(foo_t))
0

精彩评论

暂无评论...
验证码 换一张
取 消