从元组中获取一个值 [英] Getting one value from a tuple

查看:40
本文介绍了从元组中获取一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to get one value from a tuple in Python using expressions?

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

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

我知道我可以做到:

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

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

But that would add a few dozen lines to my function, doubling its length.

推荐答案

可以写

i = 5 + tup()[0]

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

Tuples can be indexed just like lists.

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

The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.

这篇关于从元组中获取一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆