简体   繁体   English

Python:元组的最后一个元素

[英]Python: last element of tuple

I would isolate the last element of a tuple like我会隔离元组的最后一个元素,例如

a = (3,5,5)
last = a[-1]

but the problem is that i have a pice ok code like this但问题是我有一个像这样的代码

if var == last:
  do something

and it takes the first 5 and not the second, how can i do to take the last one?它需要第一个5而不是第二个,我该怎么做才能取最后一个?

What you are trying to do is impossible.你试图做的事情是不可能的。 Those two fives are exactly the same.这两个五分完全一样。

However, when iterating over the tuple you can check if you reached the last element like this:但是,在迭代元组时,您可以像这样检查是否到达了最后一个元素:

a = (3, 5, 5)
for i, var in enumerate(a):
    if i == len(a) - 1:
        print 'last element:'
    print var

Demo:演示:

In [1]: a = (3, 5, 5)
In [2]: for i, var in enumerate(a):
   ...:     if i == len(a) - 1:
   ...:         print 'last element:'
   ...:     print var
   ...:
3
5
last element:
5

You can unpack tuples like this:您可以像这样解包元组:

t = (3, 5, 5)
*_, last = t
assert last == 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM