看了《Head First Python》后,觉得写的很不错,适合新手。此处为读书笔记,方便日后查看。

Python 提供了4中数据结构:list,dict,set,tuple. 每种结构都有自己的特征和用处。

1. List -- 有序可变对象集合

  • List 的定义
prices = [] # 定义空列表
temps = [32.0, 212.0, 0.0, 81.6, 100.0, 45.3] # 存储浮点型
words = ['hello','word'] # 存储字符串
car_details = ['Toyota', 'RAV2', 2.2, 60808] # 列表中可以存储混合类型数据
everyting = [prices, temps, words, car_details] # 列表里放置列表
  • List 常用操作,以下操作直接影响list的值。
fruit=['banana','orange','strawberry']

# 打印列表中全部元素
for v in fruit:
print(v) # 判断列表中是否存在某个元素,若不存在加入到列表中。
if 'apple' not in fruit:
fruit.append('apple')
print(fruit) # 打印列表长度
print(len(fruit)) # 从列表总添加元素
fruit.append('piers')
print(fruit) # 从列表中删除某个对象值
numsRem=[1,2,3,4]
numsRem.remove(3)
print('Remove result is '+str(numsRem))
# nums -> [1,2,4] # 从列表中删除某个位置(索引值)的对象
numsPop=[1,2,3,4]
numsPop.pop() #->4
print('Pop result is '+str(numsPop))
#nums->[1,2,3] # 加入一个其他列表
nums1=[1,2]
nums2=[3,4]
nums1.extend(nums2)
print(nums1) # [1,2,3,4] # 从列表的某个位置插入指定元素值
numsIns=[2,3,4]
numsIns.insert(0,1)
print(numsIns) #[1,2,3,4]
  • List 和 String 的相互转换
given_message = "It's a known issue."
print("given message original is \'" + given_message +" \'") # convert string to list
mes_list = list(given_message)
print("List given message is " + str(mes_list)) # convert list to string
given_message_after = ''.join(mes_list)
print("After converted to string is \'" + given_message_after + " \'")
  • 从list取特定字段, 以下操作除了rename以外,其他操作都是生成一个副本,不会改变原list的值。
list1=[1,2,3,4,5,6]
print ("list1 is "+ str(list1)) # It will give a alise for list1, but not copy of it. So if one of them is changed, the other one will be changed also.
list1_rename = list1
print ("list1_rename is " + str(list1_rename)) list1_rename[0]=9
print("After list1_rename[0]=9, list1_rename is " + str(list1_rename))
print("After list1_rename[0]=9, list1 is " + str(list1)) # Copy a list, so if one of it has been changed, the other will not be changed.
list1_copy = list1.copy()
print("list1_copy is " + str(list1_copy)) list1_copy[0]= 8
print("After list1_copy[0]= 8, list1_copy is " + str(list1_copy))
print("After list1_copy[0]= 8, list1 is " + str(list1)) # Get value by index
print("list 1 is " + str(list1)) print("first value is " + str(list1[0]))
print("last value is " + str(list1[-1])) #navigate index get the value from the end.
print("Value for every 3 index is " + str(list1[0:5:3]))
print("Value from index 3 is " + str(list1[3:]))
print("Value until index 4 is " + str(list1[:4]))
print("value all for every 2 index is " + str(list1[::2])) # get back ward value
print("Backward value for list1 is " + str(list1[::-1]))
print("Backward value for target range is " + str(list1[4:1:-1]))

2. Dict:

Dict -- 无序的键/值对集合

  • Dict的定义
dict1 = {}
dict_person = {'Name':'Steven','Gender':'Male','Occupation':'Researcher','Home Planet':'Betelgeuse Seven'} print("dict1 is "+ str(dict1))
print("dict_person" + str(dict_person))
  • Dict的常用操作
dict_person = {'Name':'Steven','Gender':'Male','Occupation':'Researcher','Home Planet':'Betelgeuse Seven'} 

# Get value by index
print("dict_person's name is " + str(dict_person['Name'])) # Add an key and value
dict_person['Age']= 33
print("After dict_person['Age']= 33, dict_person's new:value is " + str(dict_person)) # 遍历dict中的所有key
for k in dict_person:
print(k) # 遍历dict中的所有value
for k in dict_person:
print(dict_person[k]) # 遍历dict中的所有值
for k in dict_person:
print(k +":" + str(dict_person[k]) + "\t") # 遍历dict中的所有值
for k,v in dict_person.items():
print(k +":" + str(dict_person[k]) + "\t") # 遍历dict中的所有值(按顺序显示)
for k,v in sorted(dict_person.items()):
print(k +":" + str(dict_person[k]) + "\t") # 用字典记录频度, 输出给定字符串中元音出现的次数
count_for_string = 'Hello, hello, how are you'
vowels = ['a','e','i','o','u']
found ={}
for k in count_for_string:
if k in vowels:
found.setdefault(k,0)
found[k] +=1
  • 字典的嵌套(也就是表)
from pprint  import pprint 

person={}

person['Mother']={'Name':'Luky','Age':'','Sex':'Female'}
person['Father']={'Name':'Alex','Age':'','Sex':'Male'}
person['Son1']={'Name':'Ethan','Age':'','Sex':'Male'}
person['Son2']={'Name':'Ringo','Age':'','Sex':'Female'} # 显示整张嵌套列表
for k,v in sorted(person.items()):
print(str(k) + ':' + str(v)) for k,v in sorted(person.items()):
pprint(str(k) + ':' + str(v)) # 显示嵌套列表的某个值
print(person['Mother']['Age'])

3. Set

Set -- 无序唯一对象集合(不允许有重复,可以用于去重)

  • Set 的定义:
# 定义空字符串
set_a=()
print(set_a) # 从列表创建集合
set_volew=set('aaioeuu')
print(set_volew)
  • Set的常用:
# 并集
volews=set('aeiou')
world="Hello,Apple"
union_letters=volews.union(set(world))
print(union_letters) # 差集(A-B),这里是volews letter - world letter
diff_letters=volews.difference(set(world))
print(diff_letters) # 交集
inst_letters=volews.intersection(set(world))
print(inst_letters)

4. Tuple

Tuple-- 有序不可变对象集合,其实也是一个一旦创建(并填充数据)就不能改变的列表,这样性能更好。

  • 元组的定义
# 元组的定义
vowels_tuple=('a','e','i','o','u')
print(vowels_tuple)
  • 元组常用操作
# 给元组更新值会报错,因为元组值是不能变的。
# 如vowels_tuple[2]='A' 会报TypeError: 'tuple' object does not support item assignment # 显示某个元素
print(vowels_tuple[0]) # 只有一个对象的元组赋值一定要加','号,否则不会被视为元组.
tuple=('python')
print(type(tuple)) # <class 'str'> tuple2=('python',)
print(type(tuple2)) # <class 'tuple'>

欢迎转载,如需转载请注明出处。

Python 3 -- 数据结构(list, dict, set,tuple )的更多相关文章

  1. Python中内置数据类型list,tuple,dict,set的区别和用法

    Python中内置数据类型list,tuple,dict,set的区别和用法 Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, ...

  2. Python:Base2(List和Tuple类型, 条件判断和循环,Dict和Set类型)

    1.Python创建list: Python内置的一种数据类型是列表:list.list是一种有序的集合,可以随时添加和删除其中的元素. 比如,列出班里所有同学的名字,就可以用一个list表示: &g ...

  3. (python数据分析)第03章 Python的数据结构、函数和文件

    本章讨论Python的内置功能,这些功能本书会用到很多.虽然扩展库,比如pandas和Numpy,使处理大数据集很方便,但它们是和Python的内置数据处理工具一同使用的. 我们会从Python最基础 ...

  4. python的数据结构分类,以及数字的处理函数,类型判断

    python的数据结构分类: 数值型 int:python3中都是长整形,没有大小限制,受限内存区域的大小 float:只有双精度型 complex:实数和虚数部分都是浮点型,1+1.2J bool: ...

  5. Python 基本数据结构

    Python基本数据结构 数据结构:通俗点儿说,就是存储数据的容器.这里主要介绍Python的4种基本数据结构:列表.元组.字典.集合: 格式如下: 列表:list = [val1, val2, va ...

  6. Python高级数据结构-Collections模块

    在Python数据类型方法精心整理,不必死记硬背,看看源码一切都有了之中,认识了python基本的数据类型和数据结构,现在认识一个高级的:Collections 这个模块对上面的数据结构做了封装,增加 ...

  7. 05-深入python的set和dict

    一.深入python的set和dict 1.1.dict的abc继承关系 from collections.abc import Mapping,MutableMapping #dict属于mappi ...

  8. Python原生数据结构增强模块collections

    collections简介 python提供了4种基本的数据结构:list.tuple.dict.set.基本数据结构完全可以hold住所有的场景,但是在处理数据结构复杂的场景时,这4种数据结构有时会 ...

  9. 『Python基础-9』元祖 (tuple)

    『Python基础-9』元祖 (tuple) 目录: 元祖的基本概念 创建元祖 将列表转化为元组 查询元组 更新元组 删除元组 1. 元祖的基本概念 元祖可以理解为,不可变的列表 元祖使用小括号括起所 ...

随机推荐

  1. 2018/09/13《涂抹MySQL》【MySQL复制特性】学习笔记(六)

    推荐一首歌 - <可不可以>张紫豪 好吧,随便从排行榜上找了一首 读 第十一章<MySQL的复制特性> 总结 1:复制(Replication) 应用场景? - 提高性能 (通 ...

  2. HashMap如何解决取Value值为Null

    场景: 用HashMap方法时候,取Keys时候自认为敲的肯定是准确无误,然后能得到对应的Values 值.  但写脚本代码时候不好习惯,没事总喜欢敲个空格建,导致取Keys之后多空格. Featur ...

  3. 洛谷P3237 米特运输 [HNOI2014] hash/二进制分解

    正解:hash/二进制分解 解题报告: 传送门! umm首先提取下题意趴QAQ 大概是说给一棵树,每个点有一个权值,要求修改一些点的权值,使得同一个父亲的儿子权值相同,且父亲的权值必须是所有儿子权值之 ...

  4. 【pyqtgraph绘图】安装pyqtgraph

    解读官方API-安装 安装 参考:http://www.pyqtgraph.org/documentation/installation.html 根据您的需要,有许多不同的方式来安装pyqtgrap ...

  5. SQL存储过程分页

    CREATE PROC ZDY_FY(@Pages INT, @pageRow INT) --@Pages第几页 @pageRow每页显示几行 AS BEGIN DECLARE @starNum IN ...

  6. 2017-2018-2 20165236 实验三《Java面向对象程序设计》实验报告

    2017-2018-2 20165236 实验三<Java面向对象程序设计>实验报告 一.实验报告封面 课程:Java程序设计            班级:1652 姓名:郭金涛     ...

  7. v-show 和 v-if 对 v-chart的影响

    借鉴:https://blog.csdn.net/xiaxiangyun/article/details/78909991 使用v-show控制tab切换 其中一个tab数据请求后显示第二个tab,第 ...

  8. numpy的searchsorted细品

      import numpy as np a= np.arange(20) pos_left = a.searchsorted(3)    #也可以写成np.searchsorted(a, 3), 注 ...

  9. python的join用法

    1.使用方式: 字符串.join(序列) date = "".join(["2018-12-28", "00:00:00"])

  10. Centos7 zookeeper单机/集群安装详解和开机自启

    ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是Google的Chubby一个开源的实现,是Hadoop和Hbase的重要组件.它是一个为分布式应用提供一致性服务的软件,提供的功 ...