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))
精彩评论