从元组中获取一个值

新手上路,请多包涵

有没有一种方法可以使用表达式从 Python 中的元组中获取一个值?

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

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

我知道我可以这样做:

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

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

原文由 BCS 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 264
2 个回答

你可以写

i = 5 + tup()[0]

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

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

原文由 David Z 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于将来寻找答案的任何人,我想对这个问题给出更清晰的答案。

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

希望这能为那些需要它的人进一步解决问题。

原文由 AbdulMueed 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题