python的数据类型
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python的数据类型相关的知识,希望对你有一定的参考价值。
基本数据类型:
>>数和字符串
列表:
>>python中没有数组的概念,与数组最接近的概念是列表和元祖,列表是存储一连串元素的容器
>>> str = [‘ab‘,‘cd‘,‘ef‘,‘g‘]
>>> print(str[3])
g
>>修改列表中的内容
>>> str = [‘ab‘,‘cd‘,‘ef‘,‘g‘]
>>> str[3] = ‘gh‘
>>> print (str)
[‘ab‘, ‘cd‘, ‘ef‘, ‘gh‘]
元祖:python中没有数组的概念,与数组最接近的概念是列表和元祖,元祖是存储一连串元素的容器
>>> str = (‘ab‘,‘cd‘,‘ef‘,‘g‘)
>>> print(str[1])
cd
>>只读取不能修改
>>> str = (‘ab‘,‘cd‘,‘ef‘,‘g‘)
>>> abc = str[2]
>>> print(abc)
ef
>>> str[0] = ‘a‘
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
str[0] = ‘a‘
TypeError: ‘tuple‘ object does not support item assignment
集合:
>>python中集合主要有两个功能:
>>建立关系
>>> a = set(‘abcdef‘)
>>> b = set(‘abc‘)
>>> x = a&b #交集
>>> print(x)
{‘c‘, ‘a‘, ‘b‘}
>>> y = a|b #并集
>>> print(y)
{‘b‘, ‘e‘, ‘f‘, ‘c‘, ‘a‘, ‘d‘}
>>> z = a-b #差集
>>> print(z)
{‘f‘, ‘d‘, ‘e‘}
>>消除重复元素
>>> a = (‘abcdabcabc‘)
>>> new = set(a)
>>> print(new)
{‘c‘, ‘b‘, ‘a‘, ‘d‘}
字典:
也叫作关联数组,在{}以键值对的形式存储
>>> dic = {‘name‘:‘xiaoxiao‘,‘age‘:1,‘city‘:‘beijing‘}
>>> print(dic)
{‘age‘: 1, ‘city‘: ‘beijing‘, ‘name‘: ‘xiaoxiao‘}
>>> print(dic[‘name‘])
xiaoxiao
>>添加修改字典
>>> dic = {‘name‘:‘xiaoxiao‘,‘age‘:1}
>>> print(dic)
{‘age‘: 1, ‘name‘: ‘xiaoxiao‘}
>>> dic[‘city‘] = ‘beijing‘
>>> print(dic)
{‘age‘: 1, ‘city‘: ‘beijing‘, ‘name‘: ‘xiaoxiao‘}
>>> dic[‘age‘] = 0
>>> print(dic)
{‘age‘: 0, ‘city‘: ‘beijing‘, ‘name‘: ‘xiaoxiao‘}
以上是关于python的数据类型的主要内容,如果未能解决你的问题,请参考以下文章