从元组中获取一个值
- 2025-03-13 09:08:00
- admin 原创
- 66
问题描述:
有没有办法使用表达式从 Python 中的元组中获取一个值?
def tup():
return (3, "hello")
i = 5 + tup() # I want to add just the three
我知道我能做到:
(j, _) = tup()
i = 5 + j
但这会给我的函数添加几十行代码,使其长度加倍。
解决方案 1:
你可以写
i = 5 + tup()[0]
元组可以像列表一样被索引。
元组和列表之间的主要区别在于元组是不可变的 - 您不能将元组的元素设置为不同的值,也不能像列表中那样添加或删除元素。但除此之外,在大多数情况下,它们的工作原理几乎相同。
解决方案 2:
对于将来任何寻找答案的人,我都想对这个问题给出更清晰的答案。
# for making a tuple
my_tuple = (89, 32)
my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)
# to concatenate tuples
another_tuple = my_tuple + my_tuple_with_more_values
print(another_tuple)
# (89, 32, 1, 2, 3, 4, 5, 6)
# getting a value from a tuple is similar to a list
first_val = my_tuple[0]
second_val = my_tuple[1]
# if you have a function called my_tuple_fun that returns a tuple,
# you might want to do this
my_tuple_fun()[0]
my_tuple_fun()[1]
# or this
v1, v2 = my_tuple_fun()
希望这可以为有需要的人提供进一步的帮助。
解决方案 3:
一般的
元组的单个元素a
可以以类似索引数组的方式访问
通过a[0]
,,a[1]
...,取决于元组中元素的数量。
例子
如果你的元组是a=(3,"a")
a[0]
产量3
,a[1]
产量"a"
具体回答问题
def tup():
return (3, "hello")
tup()
返回一个2元组。
为了“解决”
i = 5 + tup() # I want to add just the three
您选择3 项的方式:
tup()[0] # first element
综上所述:
i = 5 + tup()[0]
替代方案
使用 Gonamedtuple
可以按名称(和索引)访问元组元素。详细信息请参阅https://docs.python.org/3/library/collections.html#collections.namedtuple
>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
3
>>> m.mynumber
3
>>> m[1]
'hello'
>>> m.mystring
'hello'
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD