有没有办法从python中使用表达式从元组中获取一个值?
def Tup():
return (3,"hello")
i = 5 + Tup(); ## I want to add just the three
Run Code Online (Sandbox Code Playgroud)
我知道我可以这样做:
(j,_) = Tup()
i = 5 + j
Run Code Online (Sandbox Code Playgroud)
但这会给我的功能增加几十行,增加一倍.
Dav*_*d Z 187
你可以写
i = 5 + Tup()[0]
Run Code Online (Sandbox Code Playgroud)
元组可以像列表一样编入索引.
元组和列表之间的主要区别在于元组是不可变的 - 您不能将元组的元素设置为不同的值,或者从列表中添加或删除元素.但除此之外,在大多数情况下,它们的工作方式基本相同.
Abd*_*eed 48
对于将来寻找答案的人,我想对这个问题给出更明确的答案.
# for making a tuple
MyTuple = (89,32)
MyTupleWithMoreValues = (1,2,3,4,5,6)
# to concatinate 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()
Run Code Online (Sandbox Code Playgroud)
希望这能为某些人进一步清理.
a可以以类似索引数组的方式访问元组的单个元素
via a[0], a[1], ... 取决于元组中元素的数量。
如果你的元组是a=(3,"a")
a[0]产量3,a[1]产量"a"def tup():
return (3, "hello")
Run Code Online (Sandbox Code Playgroud)
tup()返回一个 2 元组。
为了“解决”
i = 5 + tup() # I want to add just the three
Run Code Online (Sandbox Code Playgroud)
您通过以下方式选择3:
tup()[0] # first element
Run Code Online (Sandbox Code Playgroud)
所以一起:
i = 5 + tup()[0]
Run Code Online (Sandbox Code Playgroud)
随之而来的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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
283967 次 |
| 最近记录: |