从元组中获取除已知元素以外的值如何操作?

huangapple go评论64阅读模式
英文:

How to get value from tuple except known one?

问题

我知道其中一个元素是1,但位置未知,我需要获取第二个元素的值,而不是1。在Python中有没有一种方法可以做到这一点,而不需要遍历元组?

英文:

Suppose we have a tuple with two elements:

a = (1, N)

or

a = (N, 1)

I know that one of the elements is 1, the position is unknown and I need to get value of second element other than 1.

Is there a way in Python to get it without iterating the tuple?

答案1

得分: 3

内置的True和False值,在整数的上下文中分别等于1和0。因此,在没有显式的if/else情况下:

N = 99

a = 1, N
b = N, 1

print(a[a[0]==1])
print(b[b[0]==1])

输出:

99
99
英文:

The built-in values of True and False, when used in the context of an integer, equate to 1 and 0 respectively. Therefore with no explicit if/else:

N = 99

a = 1, N
b = N, 1

print(a[a[0]==1])
print(b[b[0]==1])

Output:

99
99

答案2

得分: 1

尝试使用if/else语句:

if a[0] == 1:
    N = a[1]
else:
    N = a[0]

或者,为了缩短为一行,你可以使用三元运算符:

N = a[0] if a[1] == 1 else a[1]
英文:

Try use an if/else statement

if a[0] == 1:
   N = a[1]
else:
   N = a[0]

Or, to shorten this to one line, you could use the ternary operator:

N = a[0] if a[1] == 1 else a[1]

答案3

得分: 0

你可以使用 if/else

a = (1, N)  #或者 a = (N, 1)

print(a[0] if a[0]!=1 else a[1])

#输出
N
英文:

You can go with if/else

a = (1, N)  #or a = (N, 1)

print(a[0] if a[0]!=1 else a[1])

#output
N

huangapple
  • 本文由 发表于 2023年5月13日 16:57:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241884.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定