英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论