Python_03_元组

2018-11-27  本文已影响0人  像你这样优秀的人

元组

1 简介

2 元组的定义

   single_tuple = (5)
   type(single_tuple)
<class 'int'>

| 当Python的解释器发现有()时,会忽略,只读取括号里面的数值,解决这个问题只需要加一个逗号,(5,)

   single_tuple = (5,)
   type(single_tuple)
<class 'tuple'>
info_tuple=("zhangsan",18,1.75)

3 元组的方法

方法 描述
index(数据) 查找元组某个元素的索引
count(数据) 查看某个元素在元组中出现的次数
  info_tuple = ("zhangsan",18,1.75)

  # 1、取值和取索引
  print(info_tuple[0])
  print(info_tuple.index("zhangsan"))

  # 2、统计计数
  print(info_tuple.count(18))

4 循环遍历

  info_tuple = ("zhangsan",18,1.75)

  #使用迭代遍历元组
  for my_info in info_tuple:
      # print(my_info)
      print("%s 年龄是 %d 身高是 %.2f" % info_tuple)

| 由于元组有多种数据类型,回想多个变量的输出print("%s 年龄是 %d 身高是 %.2f" % ("zhangsan",18,1.75)),后面的()就是元组,所以当输出多个数据类型,我们就可以用元组变量代替。

5 元组和列表之间的转换

list(元组)

>>> num_list=[1,2,3,4,5]
>>> type(num_list)
<class 'list'>
>>> num_tuple = tuple(num_list)
>>> type(num_tuple)
<class 'tuple'>
>>> num_tuple = ("c10",15,20)
>>> num_list = list(num_tuple)
>>> type(num_list)
<class 'list'>
上一篇下一篇

猜你喜欢

热点阅读