从元组中获取一个值

205 投票
3 回答
571377 浏览
提问于 2025-04-16 00:32

有没有办法在Python中用表达式从元组中获取一个值呢?

def tup():
  return (3, "hello")

i = 5 + tup()  # I want to add just the three

我知道我可以这样做:

(j, _) = tup()
i = 5 + j

但是这样会让我的函数多出几十行代码,长度变成原来的两倍。

3 个回答

9

一般信息

你可以像访问数组一样,通过索引来访问元组 a 中的单个元素。

比如说,你可以用 a[0]a[1] 等等,具体取决于元组里有多少个元素。

例子

假设你的元组是 a=(3,"a")

  • a[0] 会得到 3
  • a[1] 会得到 "a"

具体回答问题

def tup():
  return (3, "hello")

tup() 会返回一个包含两个元素的元组。

为了“解决”这个问题,

i = 5 + tup()  # I want to add just the three

你可以通过选择 3 来实现:

tup()[0]    # first element

所以总的来说:

i = 5 + tup()[0]

替代方案

你可以使用 namedtuple,这样可以通过名字(也可以通过索引)来访问元组的元素。详细信息可以查看 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'
86

对于将来有需要的人,我想给出一个更清晰的答案来回应这个问题。

# 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()

希望这能进一步帮助那些需要的人理解。

260

你可以这样写

i = 5 + tup()[0]

元组可以像列表一样进行索引。

元组和列表之间的主要区别在于,元组是不可变的——你不能把元组里的元素改成其他值,也不能像列表那样添加或删除元素。不过在大多数情况下,它们的使用方式基本是一样的。

撰写回答