Python里的元组、列表和字典这3中数据类型都有哪些区别

Python里的元组、列表和字典这3中数据类型都有哪些区别

List 数据类型

列表包含用逗号分隔并括在方括号[]中的项,列表与c语言中的数组非常相似,一个不同之处在于:列表的所有项可以是不同的数据类型,而C语言中数组只能是同一种数据类型

  1. list = [123,'abcd',10.2,'d']
  2. 可以是任何数据类型或单个数据类型的列表
  3. print(list)
  4. 输出 [123,'abcd',10.2,'d']
  5. print(list[0:2])
  6. 输出前2个列表项 [123,'abcd']
  7. list1 = ['hello','world']
  8. print(list1 * 2)
  9. 将会出现2 ['hello','world','hello','world']
  10. print(list + list1)
  11. 这两个列表用“+”号将会被连接
  12. 输出:[123,'abcd',10.2,'d','hello','world']

Dictionary 数据类型

字典由键值对组成(类似于java中的HashMap),它由大括号{}包围,可以使用方括号[]通过key访问值或者赋值

  1. dic={'name':'red','age':10}
  2. print(dic)
  3. 会输出整个字典 {'name':'red','age':10}
  4. print(dic['name'])
  5. 输出keyname的值: 'red'
  6. print(dic.values())
  7. 输出字典所有值 ['red',10]
  8. print(dic.keys())
  9. 输出字典所有的键 ['name','age']

Tuple 数据类型

列表被括在括号[]中,它们的元素可以更改,列表长度也可以被更改。

而元组被括在括号()中,它们的元素不可以更改,元组是完全不可变的。

  1. tuple = (123,'hello')
  2. tuple1 = ('world')
  3. print(tuple)
  4. 将输出整个元组: (123,'hello')
  5. print(tuple[0])
  6. 将输出元组中第一个值 . (123)
  7. print(tuple + tuple1)
  8. 会输出: (123,'hello','world'),注意这里并没有去改变他们各自的值
  9. tuple[1]='update'
  10. 这里会报错,因为你尝试更改它的值

结论

1、元组是不可变的,而列表、字典是可变的

​ 元组是不可变对象,对象一旦生成,它的值将不能更改;列表是可变对象,对象生成后,可以对其元素进行更改、添加、删除、清空、排序等操作。

2、元组通常是由不同的数据组成,而列表是相同的数据队列

​ 元组表示的是结构,而列表表示的是顺序。列表的权限远大于元组。

3、列表不能作为字典的key值,而元组可以。字典的键是唯一的。

点赞 ( 0 )

6 条评论

  1. Spott oon with this write-up, I absolutely think ths website needs much more attention. I'll probably be returning to reaad through more, thanks forr tthe info!

  2. https://xxxtube2022.com

    I'm gone to ssay too my littke brother, that he should also pay a quick visit tthis webpwge on regular basis too obtain updated fom hottest information.

  3. dev.xxxcrunch.com

    Hey! This is myy first comment hefe so I just wanted tto give a qhick shou oout andd say I trulpy enjoy reqding your blog posts. Can you sugest any other blogs/websites/forums thwt ggo over thhe same topics? Many thanks!

  4. I lkke it when people get toggether and share ideas. Great website, coninue thee good work!

  5. jablex.com

    Hi, i think that i saw you visited my blog thgus i cae to “return the favor”.I'm trying tto find things to improve myy site!I suppose itts ok to use some of your ideas!!

  6. Mathew

    If some one desires to be updated with hottest technologies after that he must be go to see this web page and be up to date everyday.

发表评论

人生在世,错别字在所难免,无需纠正。

插入图片
s
返回顶部