我有一个库函数返回一个 tuple
看起来像这样
def some_function(some_string):
does something
return (text,id)
现在我想将从 some_function 返回的文本作为参数传递给另一个函数。问题是该函数还有其他参数,我不想将整个元组作为指针传递。我还需要检索许多由 some_string 的不同值生成的文本。
根据满足的条件,我想调用另一个看起来像这样的函数
if abcd:
other_function(name,phone,**some_function("abcd")**,age)
elif xyz:
other_function(name,phone,**some_function("xyz")**,age)
else:
other_function(name,phone,**some_function("aaaa")**,age)
那么我应该用什么替换 some_function("abcd") 以便它只发送文本而不是文本和 id 作为参数?
other_function 是这样定义的
def other_function(name,phone,text,age):
...
return
我自己想出的一个解决方案是创建另一个只返回文本的函数。
def returntextonly(some_string):
self.some_string = some_string
(text,id) = some_function(some_string)
return text
然后像这样调用other_function
if abcd:
other_function(name,phone,returntextonly("abcd"),age)
我主要使用 C++ 编程,最近才开始学习 Python。我想知道是否有比创建一个仅返回元组的一个元素的新函数更好的解决方案。
感谢阅读。
最佳答案
您可以将其运行为:
other_function(name, phone, some_function("abcd")[0], age)
无需定义额外的 if
语句、包装函数等,因为您只想传递从原始函数返回的元组的第一个元素。
对于一般情况,这变成:
other_function(name, phone, some_function(some_string)[0], age)
请注意,元组是另一个(不可变的)迭代器,它的元素可以像在列表中一样使用常规索引访问。
关于python - 将元组的一个元素作为参数与其他参数一起传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29583682/