python 中的元组|疫情期间日更(6)

###Tuple()元组
元组代表多个元素组成的序列。
元组和列表相似,元组的索引也是从0开始。不同之处在于,元组中的元素不能修改,定义元组用()。

info_tuple=("xiaoming",22,164)
a=type(info_tuple)
print(a)

输出结果为:

<class 'tuple'>

从列表中获取数据用索引的方式,同样元组中获取数据也用索引的方式。

info_tuple=("xiaoming",22,164)
a=info_tuple[0]
print(a)

输出结果为:

xiaoming

###定义空元组

info_tuple=()
print(type(info_tuple))

输出结果为:

<class 'tuple'>

###定义一个只包含一个元素的元组
感觉好像很容易的样子。我们按照我们的想法敲一下代码试一下吧

info_tuple=(5)
print(type(info_tuple))

输出结果居然为:

<class 'int'>

那么为什么会这个样子呢?
在这样一个代码,python的解释器在读取(5)时会自动忽略5左右两边的括号前面,把重点放在了括号里面的东西,它是什么类型,前面指定的变量就是什么类型。我们再来验证一下吧。

info_tuple=(7.8)
print(type(info_tuple))

输出结果为:

<class 'float'>

那么如何定义一个只包含一个元素的元组呢?

扫描二维码关注公众号,回复: 9649290 查看本文章
info_tuple=(5,)
print(type(info_tuple))

输出结果为:

<class 'tuple'>

这里说的都是元组的基础,后面的以后说。

发布了18 篇原创文章 · 获赞 12 · 访问量 2247

猜你喜欢

转载自blog.csdn.net/xiaoyun5555/article/details/104445290