1 列表

1.1 定义与索引

在Python中,第一个列表元素的下标为 0通过将索引指定为 -1

可以让Python返回最后一个列表元素

  1. inventory = ['sword', 'armor', 'shield',
  2. 'big sword', 'big shiled'];
  3. print(inventory[-1]);

1.2 修改 添加 删除

1.2.1 修改元素

  1. inventory = ['sword', 'armor', 'shield',
  2. 'big sword', 'big shield'];
  3. inventory[-1] = 'small shield'
  4. print(inventory)
  5. '''
  6. 运行结果:
  7. ['sword', 'armor', 'shield', 'big sword', 'small shield']
  8. '''

1.2.2 添加元素

  • 在列表末尾添加元素
  1. inventory1 = ['sword', 'armor', 'shield',
  2. 'big sword'];
  3. inventory1.append('small shield');
  4. print(inventory1)
  5. #结果:['sword', 'armor', 'shield', 'big sword', 'small shield']
  • 在列表中插入元素
  1. inventory2 = ['armor', 'shield',
  2. 'big sword', 'small shield'];
  3. inventory2.insert(0, 'sword');
  4. print(inventory2)
  5. #结果:['sword', 'armor', 'shield', 'big sword', 'small shield']

1.2.3 删除元素

  • 使用 del 语句删除元素-----可以是任意位置
  1. inventory = ['sword', 'armor', 'shield',
  2. 'big sword', 'big shield'];
  3. del inventory[0];
  4. print(inventory)
  5. #结果:['armor', 'shield', 'big sword', 'small shield']
  • 使用 pop( ) 删除(弹出)元素-----可以是任意位置
  1. inventory = ['sword', 'armor', 'shield',
  2. 'big sword', 'big shield'];
  3. popped_inventory = inventory.pop(4);
  4. print(inventory) #结果1
  5. print(popped_inventory) #结果2
  6. #结果1:['sword', 'armor', 'shield', 'big sword']
  7. #结果2:small shield
  • 使用 remove( ) 根据值删除元素
  1. inventory = ['sword', 'sword', 'armor', 'shield',
  2. 'big sword', 'big shield'];
  3. inventory.remove('sword');
  4. print(inventory);
  5. #结果:['sword', 'armor', 'shield', 'big sword', 'small shield']

注意:它只会删除第一个指定的值

1.3 组织列表

1.3.1 使用 sort() 对列表进行 永久性 排列

  1. mylist = ['sword', 'armor', 'big shield'];
  2. mylist.sort();
  3. print(mylist);
  4. #结果1:['armor', 'big shield', 'sword']
  5. mylist.sort(reverse = True);
  6. print(mylist);
  7. #结果2:['sword', 'big shield', 'armor']

1.3.2 使用 sorted() 对列表进行 临时 排列

  1. mylist = ['sword', 'armor', 'big shield'];
  2. print(mylist); #结果1:['sword', 'armor', 'big shield'];
  3. print(sorted(mylist)); #结果2:['armor', 'big shield', 'sword']
  4. print(mylist); #结果3:['sword', 'armor', 'big shield'];

1.1.3 使用 reverse() 倒着打印列表

  1. mylist = ['sword', 'armor', 'big shield'];
  2. print(mylist.reverse());
  3. #结果:['big shield', 'armor', 'sword']

1.1.4 使用 len() 确定列表的长度

  1. mylist = ['sword', 'armor', 'big shield'];
  2. len(mylist);
  3. #结果:3

1.4 操作列表

1.4.1 for循环遍历列表

  1. magicians = ['alice', 'david', 'jack'];
  2. for magician in magicians:
  3. print(magician.title());
  4. -------------------------------------------
  5. Alice
  6. David
  7. Jack

1.4.2 避免缩进错误

  • 忘记缩进或者忘记缩进额外的代码行
  • 不必要的缩进(注意: 循环后的不必要的缩进)
  • 遗漏了冒号

1.4.3 创建数字列表

1.4.3.1 使用函数 range()

  1. print('...START...');
  2. for value in range(1, 6): #Only 1 to 5
  3. print('NO: ' + str(value));
  4. print('...OVER...');
  5. -------------------------------------------
  6. ...START...
  7. NO: 1
  8. NO: 2
  9. NO: 3
  10. NO: 4
  11. NO: 5
  12. ...OVER...

1.4.3.2 创建数字列表

  1. numbers = list(range(10, 1, -1));
  2. numbers.append(1);
  3. delete = numbers.pop(0);
  4. print("...Erase " + str(delete) + '...');
  5. print(numbers);
  6. -------------------------------------------
  7. ...Erase 10...
  8. [9, 8, 7, 6, 5, 4, 3, 2, 1]

1.4.3.3 简单的统计计算

  1. numbers = range(1, 5);
  2. print('min: ');
  3. print(min(numbers));
  4. print('max: ');
  5. print(max(numbers));
  6. print('sum: ');
  7. print(sum(numbers));
  8. -------------------------------------------
  9. min:
  10. 1
  11. max:
  12. 4
  13. sum:
  14. 10

1.4.3.4 列表推导式

  1. squares = [value**2 for value in range(1, 11)]
  2. print(squares);
  3. -------------------------------------------
  4. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

1.4.4 使用列表的一部分

1.4.4.1 切片

  1. my_food = ['pizza', 'falafel', 'carrot cake'];
  2. friend_food = my_food[0:1];
  3. #1 如果没有指定起始索引,默认从开头开始提取
  4. #2 要让切片终于末尾,类似 #1
  5. print('My favorite foods are');
  6. print(my_food);
  7. print("\nMy friend's favorite foods are");
  8. print(friend_food);
  9. -------------------------------------------
  10. My favorite foods are
  11. ['pizza', 'falafel', 'carrot cake']
  12. My friend's favorite foods are
  13. ['pizza']

1.4.4.2 遍历切片

  1. foods = ['pizza', 'falafel', 'carrot cake'];
  2. print('My favorite foods are');
  3. for food in foods[:3]:
  4. print(food.title());
  5. -------------------------------------------
  6. My favorite foods are
  7. Pizza
  8. Falafel
  9. Carrot Cake

1.4.4.3 复制列表

  1. my_food = ['pizza', 'falafel', 'carrot cake'];
  2. friend_food = my_food[:];
  3. print('My favorite foods are');
  4. print(my_food);
  5. print("\nMy friend's favorite foods are");
  6. print(friend_food);
  7. -------------------------------------------
  8. My favorite foods are
  9. ['pizza', 'falafel', 'carrot cake']
  10. My friend's favorite foods are
  11. ['pizza', 'falafel', 'carrot cake']



2 元组

列表非常适合用于存储在程序运行期间可能变化的数据集

但有时需要一系列不可修改的元素, 元组可以满足这种需求

2.1 定义元组

使用圆括号标识

  1. foods = ('pizza', 'falafel', 'carrot cake');
  2. print('My favorite foods are');
  3. for food in foods[:3]:
  4. print(food.title());
  5. -------------------------------------------
  6. My favorite foods are
  7. Pizza
  8. Falafel
  9. Carrot Cake

2.2 修改元组变量

虽然不能元组的元素,但可以给存储元组的变量赋值

  1. foods = ('pizza', 'falafel', 'carrot cake');
  2. print(foods);
  3. foods = ('sword', 'shield', 'armor');
  4. print(foods);
  5. -------------------------------------------
  6. ('pizza', 'falafel', 'carrot cake')
  7. ('sword', 'shield', 'armor')



3 字典

3.1 定义与访问

在Python中,字典 是一系列 键-值对。每个 都与一个 相关联,可以使用键来访问与之相关的值

与键相关联的 可以是 数字,字符串,列表乃至字典

事实上,可将任何Python对象用作字典中的值,但键不行

  1. fruit = {
  2. 'name': 'apple',
  3. 'color': 'red',
  4. 'quantity': 5
  5. };
  6. print(fruit['name']);
  7. print(fruit['color']);
  8. print(fruit['quantity']);
  9. -------------------------------------------
  10. apple
  11. red
  12. 5

3.1.1 注意点

  • 不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个会被记住
  • 键必须不可变,所以可以用数字,字符串或元组充当,而用列表不行

3.2 修改 添加 删除

3.2.1 修改字典中的值

  1. apple = {'color': 'green'};
  2. print('The apple is ' + apple['color'] + '.');
  3. apple['color'] = 'red';
  4. print('The apple is now ' + apple['color'] + '.');
  5. -------------------------------------------
  6. The apple is green.
  7. The apple is now red.

3.2.2 添加 键-值对

  1. fruit = {
  2. 'name': 'apple',
  3. 'color': 'red',
  4. 'quantity': 5
  5. };
  6. print(fruit);
  7. fruit['x_position'] = 0;
  8. fruit['y_position'] = 12;
  9. print(fruit);
  10. -------------------------------------------
  11. {'name': 'apple', 'color': 'red', 'quantity': 5}
  12. {'name': 'apple', 'color': 'red', 'quantity': 5, 'x_position': 0, 'y_position': 12}

3.2.3 删除 键-值对

  1. fruit = {
  2. 'name': 'apple',
  3. 'color': 'red',
  4. 'quantity': 5
  5. };
  6. print(fruit);
  7. del fruit['quantity'];
  8. print(fruit);
  9. -------------------------------------------
  10. {'name': 'apple', 'color': 'red', 'quantity': 5}
  11. {'name': 'apple', 'color': 'red'}

3.3 遍历字典

3.3.1 遍历所有的键-值对

items()

  1. people = {
  2. 'name': 'vivian',
  3. 'gender': 'man',
  4. 'hobby': 'python',
  5. };
  6. for key,value in people.items():
  7. print(key.title() + ' : ' + value.title());
  8. -------------------------------------------
  9. Name : Vivian
  10. Gender : Man
  11. Hobby : Python

3.3.2 遍历所有的键

keys()

  1. people = {
  2. 'name': 'vivian',
  3. 'gender': 'man',
  4. 'hobby': 'python',
  5. };
  6. for key in people.keyes():
  7. print(key.title());
  8. -------------------------------------------
  9. Name
  10. Gender
  11. Hobby

3.3.3 遍历所有的值

  1. people = {
  2. 'name': 'vivian',
  3. 'gender': 'man',
  4. 'hobby': 'python',
  5. };
  6. for value in people.values():
  7. print(value.title());
  8. -------------------------------------------
  9. Vivian
  10. Man
  11. Python

3.4 字典内置函数&方法

3.4.1 Python字典包含的内置函数

  1. people = {
  2. 'name': 'vivian',
  3. 'gender': 'man',
  4. 'hobby': 'python',
  5. };
函数及描述 实例
len(dict)
计算字典元素个数
>>>len(people)
3
str(dict)
输出字典,可以打印的字符串表示
>>>str(people)
{'name': 'vivian', 'gender': 'man', 'interest': 'python'}
type(variable)
返回变量类型
>>>type(people)
<class 'dict'>

3.4.2 Python字典包含的内置方法

  1. people = {
  2. 'name': 'vivian',
  3. 'gender': 'man',
  4. 'hobby': 'python',
  5. };
函数与描述 实例
dict.clear( ) >>>people.clear();
>>>len(people);
0
dict.copy( ) >>>person = people.copy();
>>>person
{'name': 'vivian', 'gender': 'man', 'hobby': 'python'}
dict.fromkeys(seq[, value])
中括号内是选填
>>> seq = ('name','sex','hobby')
>>> person = dict.fromkeys(seq)
>>> person
{'name': None, 'sex': None, 'hobby': None}
>>> person = dict.fromkeys(seq,666)
>>> person
{'name': 666, 'sex': 666, 'hobby': 666}
dict.get(key, default = None) >>> people = {
... 'name': 'vivian',
... 'gender': 'man',
... 'hobby': 'python',
... };
>>> people.get('name')
'vivian'
>>> people.get('name').title()
'Vivian'
>>> people.get('nam')
#啥都没有
dict.setdefault(key, defalut = None)
如果键不存在,将会添加键并将值设为默认值
>>> people.setdefault('nam',None)
>>> people.setdefault('name',None)
'vivian'
>>> people
{'name': 'vivian', 'gender': 'man', 'hobby': 'python', 'nam': None}
dict.update(dict2)
把 dict2 添加到指定字典 dict 中
>>> people.update({'age': 18})
>>> people
{'name': 'vivian', 'gender': 'man', 'hobby': 'python', 'nam': None, 'age': 18}
dict.pop(key[, defalut])
中括号内是选填
key:要删除的键值
返回被删除的值
>>> people.pop('name')
'vivian'
dict.popitem()
随机返回并删除字典中的最后一对键和值
如果字典已经为空,还使用它,则会报错
>>> people.popitem();
('hobby', 'python')
>>> people.popitem();
('gender', 'man')



4 集合

4.1 定义

  • 集合(set)是一个无序的不重复元素序列

  • 可以使用大括号 { } 或者 set() 函数创建集合

  • 注意:创建一个空集合必须用 set() 而不是 { } ,因为 { } 是用来创建一个空字典

  • 创建格式:

  1. parame = {value01, value02......}
  2. 或者
  3. set(value)

4.2 集合特性

  1. >>> fruits = {'apple','orange','apple','pear','orange','banana'}
  2. >>> print(fruits)
  3. #去重功能
  4. {'apple', 'banana', 'pear', 'orange'}
  5. #判断元素是否在集合内
  6. >>> 'apple' in fruits
  7. True
  8. >>> 'onion' in fruits
  9. False
  10. #两个集合之间的运算
  11. >>> a = set('sgjahsgs')
  12. >>> b = set('skajkshgs')
  13. >>> a
  14. {'s', 'g', 'j', 'a', 'h'}
  15. >>> b
  16. {'s', 'j', 'g', 'a', 'k', 'h'}
  17. >>> b - a # b 比 a 多的部分
  18. {'k'}
  19. >>> a | b # 并集
  20. {'s', 'g', 'j', 'a', 'k', 'h'}
  21. >>> a & b # 交集
  22. {'s', 'g', 'j', 'a', 'h'}
  23. >>> a ^ b # 以它们并集为全集,两者交集的补集
  24. {'k'}

4.2.1 集合推导式

  1. >>> a = {value for value in 'absjhagjgs' if value not in 'abc'}
  2. >>> a
  3. {'j', 'h', 's', 'g'}

4.3 添加 删除

4.3.1 添加元素

  1. >>> fruit = {'apple','banana','strawberry','onion'}
  2. #1 使用add(element) 如果在集合中,element元素已经存在了,则不会进行任何操作
  3. >>> fruit.add('grape')
  4. #2 使用update(x)
  5. #其参数可以是列表,元组,字典等
  6. >>> fruit.update('h')
  7. >>> fruit
  8. {'onion', 'apple', 'grape', 'banana', 'h', 'strawberry'}
  9. >>> fruit = {'apple','banana','strawberry','onion'}
  10. >>> fruit.update([1,3])
  11. >>> fruit
  12. {1, 'onion', 3, 'apple', 'banana', 'strawberry'}

4.3.2 删除元素

  1. >>> fruit
  2. {1, 'onion', 3, 'apple', 'banana', 'strawberry'}
  3. >>> fruit.remove(1) #如果集合中不存在要移除的元素,则会发生错误
  4. >>> fruit
  5. {'onion', 3, 'apple', 'banana', 'strawberry'}
  6. >>> fruit.discard(3) #如果集合中不存在要移除的元素,不会发生错误
  7. >>> fruit
  8. {'onion', 'apple', 'banana', 'strawberry'}
  9. >>> fruit.pop() #随机删除,并返回被删除的元素
  10. 'onion'
  11. >>> fruit.pop()
  12. 'apple'

4.4 集合内置方法

  1. >>> x = set('abcdf')
  2. >>> y = set('abcrg')
  3. >>> z = set('abczh')
  4. >>> m = set('dhfjk')
函数与描述 实例
set.difference(set)
返回集合的差集
>>> z = x.difference(y)
>>> z
{'d', 'f'}
set.difference_update(set)
移除两个集合都包含的元素
无返回值
>>> x.difference_update(y)
>>> x
{'f', 'd'}
set.intersection(set1, set2 ... etc)
返回集合的交集
>>> m = x.intersection(y, z)
>>> m
{'c', 'b', 'a'}
set.intersection_update(set1, set2 ... etc)
无返回值
>>> x.intersection_update(y, z)
>>> x
{'c', 'b', 'a'}
isdisjoint()
判读两个集合是否包含相同元素
如果 没有 返回True
>>> x.isdisjoint(y)
False
set.issubset(set)
判断是否是被包含
>>> x.issubset(y)
True
issuperset
判断是否包含
>>> y.issuperset(x)
True
symmetric_difference()
返回交集在并集中的补集
>>> m = x.symmetric_difference(y)
>>> m
{'g', 'r'}
symmetric_difference_update()
无返回值
>>>x.symmetric_difference_update(y)
>>> x
{'g', 'r'}
union()
返回并集
>>> n = x.union(m)
>>> n
{'f', 'b', 'd', 'h', 'k', 'a', 'c', 'j'}

【Python3】列表字典集合元组的更多相关文章

  1. python3 列表/字典/集合推导式

    '''列表推导式[结果 fox循环 if语句]'''lst = ["Python周末%s期" % i for i in range(1, 27) if i%2 == 0]print ...

  2. Python 高效编程技巧实战(2-1)如何在列表,字典, 集合中根据条件筛选数据

    Python 高效编程技巧实战(2-1)如何在列表,字典, 集合中根据条件筛选数据 学习目标 1.学会使用 filter 借助 Lambda 表达式过滤列表.集合.元组中的元素: 2.学会使用列表解析 ...

  3. python :列表 字典 集合 类 ----局部变量可以改全局变量

    #列表 字典 集合 类 ----局部变量可以改全局变量,除了整数和字符串 names=["alex","jack","luck"] def ...

  4. python基础一 -------如何在列表字典集合中根据条件筛选数据

    如何在列表字典集合中根据条件筛选数据 一:列表 先随机生成一个列表,过滤掉负数 1,普通for循环迭代判断 2,filter()函数判断,filter(函数,list|tuple|string) fi ...

  5. Python基础2 列表 字典 集合

    本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作 定义列表 ...

  6. 如何在列表,字典,集合中,根据条件筛选数据 -- Python数据结构与算法相关问题与解决技巧

    实际案例: 1.过滤掉列表 [3,9,-1,10,20,-2..]的负数 2.筛出字典{'LiLei':79,'Jim':88,'Lucy':92...}中值高于90的项 3.筛出集合 {77,89, ...

  7. Learn day3 深浅拷贝/格式化/字符串/列表/字典/集合/文件操作

    1. pass break continue # ### pass break continue # (1) pass 过 """如果代码块当中,什么也不写,用pass来 ...

  8. python中元组/列表/字典/集合

    转自:https://blog.csdn.net/lobo_seeworld/article/details/79404566

  9. python数据类型详解及列表字典集合推导式详解

    一.运算符 Python语言支持以下类型的运算符: 算术运算符 如: #!/usr/bin/env python # -*- coding:utf-8 -*- a = 5 b = 6 print(a ...

随机推荐

  1. Pytorch Linear ()简单推导

    pytorch,nn.Linear 下图中的A是权重矩阵,b是偏置. in_features输入样本的张量大小 out_features输出样本的张量大小 bias是偏置 # 测试代码 # batch ...

  2. Node.js 中的进程和线程

    线程和进程是计算机操作系统的基础概念,在程序员中属于高频词汇,那如何理解呢?Node.js 中的进程和线程又是怎样的呢? 一.进程和线程 1.1.专业性文字定义 进程(Process),进程是计算机中 ...

  3. Apache Struts 2 漏洞汇总

    Apache Struts2 是一个基于MVC设计模式的Web应用框架,会对某些标签属性(比如 id)的属性值进行二次表达式解析,因此在某些场景下将可能导致远程代码执行. Struts2特征: 通过页 ...

  4. 关于 MyBatis-Plus 分页查询的探讨 → count 都为 0 了,为什么还要查询记录?

    开心一刻 记得上初中,中午午休的时候,我和哥们躲在厕所里吸烟 听见外面有人进来,哥们猛吸一口,就把烟甩了 进来的是教导主任,问:你们干嘛呢? 哥们鼻孔里一边冒着白烟一边说:我在生气 环境搭建 依赖引入 ...

  5. Ansible的参数介绍

    安装完成ansible后查看ansible的参数:ansible -h ansible 命令格式:Usage: ansible <host-pattern> [options] ansib ...

  6. 手脱无名壳tslgame_rl

    1.使用Detect It Easy查壳,该壳未显示出壳信息,至于为何有壳,我们使用IDA打开,查看其的导入表,其中没有太多函数使用: 2.我们使用x32dbg打开,运行至入口点,此处没有pushad ...

  7. 初始C语言作业一

    1.下面哪个不是C语言内置的数据类型:( ) A.char B.double C.struct Stu D.short 解析: C语言中内置类型包括 char //字符数据类型 short //短整型 ...

  8. Android 12(S) 图像显示系统 - GraphicBuffer同步机制 - Fence

    必读: Android 12(S) 图像显示系统 - 开篇 一.前言 前面的文章中讲解Android BufferQueue的机制时,有遇到过Fence,但没有具体讲解.这篇文章,就针对Fence这种 ...

  9. 113_Power Pivot 销售订单之重复购买率及购买间隔天数相关

    博客:www.jiaopengzi.com 焦棚子的文章目录 请点击下载附件 1.背景 在论坛中看到朋友在提复购率(重复购买率)等相关问题,今天把结果贴出来. 问题原贴:计算订单中的老顾客复购率 感谢 ...

  10. MVC 调试页面路径变成 Views/Controller/Action.cshtml问题

    MVC在路由里面已经写好了路径,但是调试时地址栏还是会变成 Views/Controller/Action.cshtml,导致报404错误,找不到路径. 原因可能是你将某一页面设为了起始页,导致每次运 ...