从python tup获取一个值

2024-04-18 00:48:36 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法用表达式从python中的元组中获取一个值?

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

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

我知道我能做到:

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

但这会给我的函数增加几十行,使它的长度加倍。


Tags: theto函数addhelloreturn表达式def
2条回答

你可以写

i = 5 + Tup()[0]

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

元组和列表的主要区别在于元组是不可变的——不能将元组的元素设置为不同的值,也不能像从列表中添加或删除元素那样。但除此之外,在大多数情况下,它们的工作原理几乎相同。

对于将来寻找答案的人,我想给他们一个更清晰的答案。

# for making a tuple

MyTuple = (89,32)
MyTupleWithMoreValues = (1,2,3,4,5,6)

# to concatenate tuples
AnotherTuple = MyTuple + MyTupleWithMoreValues
print AnotherTuple

# it should print 89,32,1,2,3,4,5,6

# getting a value from a tuple is similar to a list
firstVal = MyTuple[0]
secondVal = MyTuple[1]

# if you have a function called MyTupleFun that returns a tuple,
# you might want to do this
MyTupleFun()[0]
MyTupleFun()[1]

# or this
v1,v2 = MyTupleFun()

希望这能为那些需要它的人澄清一些事情。。。

相关问题 更多 >

    热门问题