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

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

How to get value from tuple except known one?

问题

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

英文:

Suppose we have a tuple with two elements:

  1. a = (1, N)

or

  1. 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情况下:

  1. N = 99
  2. a = 1, N
  3. b = N, 1
  4. print(a[a[0]==1])
  5. print(b[b[0]==1])

输出:

  1. 99
  2. 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:

  1. N = 99
  2. a = 1, N
  3. b = N, 1
  4. print(a[a[0]==1])
  5. print(b[b[0]==1])

Output:

  1. 99
  2. 99

答案2

得分: 1

尝试使用if/else语句:

  1. if a[0] == 1:
  2. N = a[1]
  3. else:
  4. N = a[0]

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

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

Try use an if/else statement

  1. if a[0] == 1:
  2. N = a[1]
  3. else:
  4. N = a[0]

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

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

答案3

得分: 0

你可以使用 if/else

  1. a = (1, N) #或者 a = (N, 1)
  2. print(a[0] if a[0]!=1 else a[1])
  3. #输出
  4. N
英文:

You can go with if/else

  1. a = (1, N) #or a = (N, 1)
  2. print(a[0] if a[0]!=1 else a[1])
  3. #output
  4. 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:

确定