1.元组结构(Tuple)

元组由不同的元素组成,每个元素可以存储不同类型的数据,如字符串、数字甚至元组。元组创建后不能修改。

元组通常代表一行数据,而元组中的元素代表不同的数据项。

1.1元组的创建

创建时可不指定元素的个数,相当于不定长的数组,但一旦创建就不能修改元组的长度。

tuple = (元素1, 元素2, ...)

#创建并初始化
tuple = ("apple", "banana","grape", "orange" ) #创建一个空的元组
tuple = ()

创建只包含一个变量的元组时,单元素后面的逗号不能省略。因为Python无法区分变量tuple是元组还是表达式。

1.2元组的访问

tuple[n]                             #访问第n+1个元素

元组访问的特殊用法:

  • 负数索引

从元组的尾部开始技术,最尾端的元素索引表示“-1”,次尾端表示“-2”,以此类推。

  • 分片索引

分片是元组的一个子集,分片是从第1个索引到第2个索引(包含第2个索引所指向的元素)所指定的所有元素。分片索引可以为正数或者负数,两个索引之间用冒号分隔。分片的格式如下:

tuple[m:n]                             # m、n可以是0、正整数或负整数
# 表示tuple中第m+1个元素到第n个元素,不包括n+1

python称创建元组的过程为“打包”,相反,元组也可以执行解包的操作。

#  打包
tuple = ("apple", "banana","grape", "orange" ) # 解包
a, b, c, d = tuple
print (a, b, c, d) #结果为 apple banana grape orange

1.3元组的遍历

# 二元元组的遍历
tuple = ( ("apple", "banana"), ("grape", "orange"), ("melon",), ("charry",) ) for i in range( len(tuple) ):
print ("tuple[%d] : " % i , " " ,)
for j in range( len(tuple[i]) ):
print (tuple[i][j], " ",)
print() #output
tuple[0] : apple banana
tuple[1] : grape orange
tuple[2] : melon
tuple[3] : charry
tuple = ( ("apple", "banana"), ("grape", "orange"), ("melon",), ("charry",) )
for i in tuple:
for j in i:
print(j) #output
apple banana grape orange melon charry

2.列表结构

2.1列表基本操作

通常作为函数的返回类型。和元组类似,也是由一组元素组成的,列表可以实现添加、删除和查找操作,元素的值可以被修改。

# 列表操作

# 定义列表
list = [ "apple", "banana", "grape", "orange"]
print (list)
print (list[2]) # 在列表末尾添加元素
list.append("melon")
# 向列表list[1]处插入元素
list.insert(1, "charry")
print (list) # 从列表中移除grape
list.remove("grape")
print (list)
# 打印列表最后一个元素
print ( list.pop() )

2.2列表的使用

列表与元组相似,同样支持负数索引、分片以及多元列表等特性。

# 负数索引和分片的使用
list = [ "apple", "banana", "grape", "orange"]
print (list[-2]) # grape
print (list[1:3]) # ['banana', 'grape']
print (list[-3:-1]) # ['banana', 'grape'] # 二元列表的遍历
list = [ ["apple", "banana"], ["grape", "orange"], ["melon"], ["charry"] ]
for i in range( len(list) ):
print ( "list[%d] :" % i, " ",)
for j in range( len(list[i]) ):
print (list[i][j], " ",)
print()

列表的连接可以使用extend(),或使用运算符“+”或“+=”。

list1 = ["apple", "banana"]
list2 = ["grape", "orange"]
# 将list2接在list1后
list1.extend(list2)
print (list1) list3 = ["melon"]
list1 = list1 + list3
print (list1) list += ["charry"] ]
print (list1) list1 = ["apple", "banana"] * 2
print (list1)

2.3列表的查找、排序、反转

list = [ "apple", "banana", "grape", "orange"]
# 打印grape的索引
print ( list.index("grape") )
# 判断orange是否在列表中
print ( "orange" in list )
list = ["banana", "apple",  "orange", "grape"]
# 按字典序排序
list.sort()
print ("Sorted list: ", list)
# 反转
list.reverse()
print ("Reversed list: ", list)

2.4列表实现堆栈和队列

# 堆栈的实现
list = ["apple", "grape", "grape"]
list.append("orange")
print (list)
print ("弹出的元素: ", list.pop())
print (list)
 # 队列的实现

list = ["apple",  "grape", "grape"]
list.append("orange")
print (list)
print ("弹出的元素: ", list.pop(0))
print (list)

3.字典结构
字典是由“键-值”对组成的集合,字典中的“值”通过“键”来引用。

3.1字典的创建

# 字典创建格式
dictionary = {key1 : value1, key2 : value2, ...} # 空字典
dictionary = {} # 字典的创建和访问
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
print (dict) # {'a' : 'apple', 'b' : 'banana', 'g' : 'grape', 'o' : 'orange'}
print (dict["a"]) # apple print ("%s, %(a)s, %(b)s % {"a": "apple", "b": "banana"})
# 输出: {'a' : 'apple', 'b' : 'banana'}, apple, banana

3.2字典的访问

dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
#添加
dict["m"] = "melon"
# 删除
del(dict["a"])
# 修改
dict["a"] = "almond"
# 弹出字典中键位b的元素
print (dict.pop("b")
print (dict)
# 清空dict
dict.clear()
print (dict)
# 字典的遍历
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k in dict:
print ("dict[%s] = " % k, dict[k]) # output
dict[a] = apple
dict[b] = banana
dict[g] = grape
dict[o] = orange
# 字典item()的使用
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
print (dict.items()) # output
{('a' , 'apple'), ('b' , 'banana'), ('g' , 'grape'), ('o' , 'orange')} # 调用item()实现字典的遍历
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for (k,v) in dict.items():
print ("dict[%s] =" % k, v) # output
dict[a] = apple
dict[b] = banana
dict[g] = grape
dict[o] = orange

元组、列表、字典作为字典的value值时,该字典称为混合型字典。

# 混合型字典的创建格式
dict = {"key1" : (tuple), "key2" : [list], "key3" : [dictionary], ...} # 访问方法由外向内叠加

3.3字典的方法

dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
# keys()返回字典的key列表
print (dict.keys() ) # {'a', 'b', 'g', 'o'} # values()返回字典的value列表
print ( dict.values() ) # {'apple', 'banana', 'grape', 'orange'}

另一个获取value的办法是使用字典的get(),get()声明如下:

D.get(k[,d])  ->  D[k]
# k为键值,d可作为get返回值,默认值为None
# k在字典D中,返回D[K];若不在,返回参数d #get等价语句如下
D = {"key1" : "value1", "key2" : "value2"}
if "key1" in D:
print (D["key1"])
else:
print ("None") # 用例
print (dict.get("o", "apple") ) #输出键值o的值,若不存在输出apple

若要添加新元素到已存在的字典中,调用update()函数。update把一个字典的key和value全复制到另一个字典中,相当于一个合并函数。

# updat()等价语句
D = {"key1" : "value1", "key2" : "value2"}
E = {"key3" : "value3", "key4" : "value4"}
for k in E:
D[k] = E[k]
print (D) # {'key3' : 'value3', 'key2' : 'value2', 'key1' : 'value1', 'key4' : 'value4'} # 字典E中含有字典D中的key
D = {"key1" : "value1", "key2" : "value2"}
E = {"key2" : "value3", "key4" : "value4"}
for k in E:
D[k] = E[k]
print (D) # {'key2' : 'value3', 'key1' : 'value1', 'key4' : 'value4'}
# 字典的更新
dict = {"a" : "apple", "b" : "banana"}
dict2 = {"g" : "grape", "o" : "orange"}
dict.update(dict2)
print (dict) #{'a' : 'apple', 'g' : 'grape', 'b' : 'banana', 'o' : 'orange'}

字典的setdefault()可以创建新的元素并设置默认值

# 声明
D.setdefault(k[,d]) -> D.get(k,d)
若k在字典中,返回get(k,d)的结果;若不在,添加新元素D[k]并调用get(k,d)返回d的值 # 设置默认值
dict = {}
dict.setdefault("a")
print (dict) # {'a': None}
dict["a"] = "apple"
dict.setdefault("a","None")
print (dict) # {'a': 'apple'}

3.4字典的排序、复制

# 调用sorted()排序
dict = {"a" : "apple", "o" : "orange", "b" : "grape", "g" : "banana"}
print (dict) # 按照key排序
print ( sorted(dict.item(), key = lambda d: d[0]) )
# 按照value排序
print ( sorted(dict.item(), key = lambda d: d[1]) ) # lambda可用于创建匿名函数,用于返回一些计算结果。

若将字典A的内容复制到B并清除B,可以使用copy()

#copy()定义
D.copy() -> a shallow copy of D # 字典的浅拷贝
dict = {"a" : "apple", "b" : "banana"}
dict2 = {"g" : "grape", "o" : "orange"}
dict2 = dict.copy()
print (dict2)

深拷贝能够拷贝对象内部所有的数据和引用,引用相当于C语言中指针的概念,Python并不存在指针,但是变量的内存结构通过引用来维护变量。而浅拷贝只是复制数据,并没有复制数据的引用,新的数据和旧的数据使用同一块内存空间。

eg.B浅拷贝A的数据,B改变,A也改变。

deepcopy()用于深拷贝.

# 字典的深拷贝
import copy
dict = {"a" : "apple", "b" :{"g" : "grape", "o" : "orange"}}
dict2 = copy.deepcopy(dict)
dict3 = copy(dict)
dict2["b"]["g"] = "orange"
print (dict) # 不改变
dict3["b"]["g"] = "orange"
print (dict) # 改变

3.5全局字典——sys.modules模块

sys.modules是一个全局函数,这个字典是Python启动后就加载在内存中的。每当程序员导入新的模板,sys.modules都将记录这些模板。字典sys.modules对加载模板起到了缓存的作用。当模板第一次导入,sys.modules自动记录。第二次导入时,Python直接在字典中查找。

import sys
print ( sys.modules.keys() ) # keys()返回当前环境下加载的模块
print ( sys.modules.values() ) # values()返回这些模板引用路径
print ( sys.modules["os"] ) # 返回索引"os"对应的引用
#  导入模块的过滤
import sys
d = sys.modules.copy() # 把当前导入的模块信息保存到字典d中
import copy, string # 导入模块copy、string,此时sys.modules包含原有模块和新导入的模块
print ( zip( set(sys.modules) - set(d) ) ) # 使用zip进行modules过滤 # set()把字典sys.modules、字典d存入set集合中,set集合实现了减法运算符
# set(sys.modules) - set(d)返回字典d中没有、而字典sys.modules中存在的模块
# 然后用zip()对set集合“解包”,返回一个列表。该列表就是import copy,string语句导入的模块
# output: [('copy',), ('strop',), ('string',)]

4.序列

是具有索引和切片能力的集合。元组、列表和字符串具有通过索引访问某个具体的值,或通过切片返回一段切片的能力,因此元组、列表和字符串都属于序列。

PS:  Python中的X[:,0]和X[:,0:1]的相关操作

Python学习笔记3(数据结构)的更多相关文章

  1. python学习笔记五——数据结构

    4 . python的数据结构 数据结构是用来存储数据的逻辑结构,合理使用数据结构才能编写出优秀的代码.python提供的几种内置数据结构——元组.列表.字典和序列.内置数据结构是Python语言的精 ...

  2. Python学习笔记系列——数据结构相关

    Python有4种数据结构:列表(list).字典(dictionary).元组(Tuple).集合(set).从最直接的感官上来说,这四种数据结构的区别是:列表中的元素使用方括号括起来,字典和集合是 ...

  3. Python学习笔记——基本数据结构

    列表list List是python的一个内置动态数组对象,它的基本使用方式如下: shoplist = ['apple', 'mango', 'carrot', 'banana'] print 'I ...

  4. Python学习笔记(3)--数据结构之列表list

    Python的数据结构有三种:列表.元组和字典 列表(list) 定义:list是处理一组有序项目的数据结构,是可变的数据结构. 初始化:[], [1, 3, 7], ['a', 'c'], [1, ...

  5. Python学习笔记(5)--数据结构之字典dict

    字典(dict) 定义:键值对集合 初始化:{}, {'1' : 'abc', '2' : 'def'} 1.增加:单个数据直接赋值  update(dict2) ---把dict2的元素加入到dic ...

  6. Python学习笔记(4)--数据结构之元组tuple

    元组(tuple) 定义:tuple和list十分相似,但是tuple是不可变的,即不能修改tuple 初始化:(), ('a', ) , ('a', 'b')   //当只有一个元素时,需加上逗号, ...

  7. python学习笔记整理——字典

    python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...

  8. python学习笔记整理——元组tuple

    Python 文档学习笔记2 数据结构--元组和序列 元组 元组在输出时总是有括号的 元组输入时可能没有括号 元组是不可变的 通过分拆(参阅本节后面的内容)或索引访问(如果是namedtuples,甚 ...

  9. python学习笔记之module && package

    个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...

  10. Python学习笔记,day5

    Python学习笔记,day5 一.time & datetime模块 import本质为将要导入的模块,先解释一遍 #_*_coding:utf-8_*_ __author__ = 'Ale ...

随机推荐

  1. SpringMVC中用@ParamVariable传递的参数包含斜杠(/)时,匹配不了报404错误的解决方案

    今天做网站[标签]筛选功能时,出现了这么个奇葩的问题. 我是直接通过<a>标签中href来跳转的,url中包含汉字 <a href="/tags/标签A"> ...

  2. Combination Sum,Combination Sum II,Combination Sum III

    39. Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique co ...

  3. C++中的类指针

    代码: #include <iostream> #include <string> #include <cstdio> using namespace std; c ...

  4. JavaScript语法学习笔记

    1.关于执行JavaScript代码的方法: 第一种方法是将JavaScript代码放到文档<head>标签中的<script>标签之间: <head>     & ...

  5. 大转盘Demo

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  6. 如何从数据库(实体提供者)读取安全用户(转自http://wiki.jikexueyuan.com/project/symfony-cookbook/entity-provider.html)

    Symfony 的安全系统可以通过活动目录或开放授权服务器像数据库一样从任何地方加载安全用户.这篇文章将告诉你如何通过一个 Doctrine entity 从数据库加载用户信息. 前言 在开始之前,您 ...

  7. 如何让checkbox复选框只能单选

    function框架div 如何让checkbox复选框只能单选 在项目开发中遇到一个这样的问题,要让一列复选框架在任何时间段内只能选择一个. 有人说怎么不用单选框了,因为单选框一旦选择了就不能取消选 ...

  8. Linux - Reset a MySQL root password

    Use the following steps to reset a MySQL root password by using the command line interface. Stop the ...

  9. Shell脚本调试技术

    http://www.ibm.com/developerworks/cn/linux/l-cn-shell-debug/ 一. 前言 shell编程在unix/linux世界中使用得非常广泛,熟练掌握 ...

  10. OpenWRT 编译 error GNU libiconv not in use but included iconv.h is from...

    OpenWRT 编译 error GNU libiconv not in use but included iconv.h is from... 编译的时候碰到一个常见的错误,但是却在一个陌生的地方爆 ...