python字典和列表使用的要点
2023-09-27 14:26:13 时间
dicts = {}
lists = []
dicts['name'] = 'zhangsan'
lists.append(dicts)
这时候lists的内容应该是[{'name': 'zhangsan'}]
现在改变dicts的值
dicts['name'] = 'lisi'
因为是引用的dicts的值,所以这时候lists的内容应该是[{'name': 'lisi'}]
如果使用
if dicts not in lists:
lists.append(dicts)
这是永远不会执行的,因为lists的值引用了dicts的值,所以lists的值永远和dicts的值一样,在循环中要将dicts重新设置成一个新字典
在字典中循环时,关键字和对应的值可以使用 iteritems() 方法同时解读出来:
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
在序列中循环时,索引位置和对应值可以使用 enumerate() 函数同时得到:
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
同时循环两个或更多的序列,可以使用 zip() 整体打包:
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
需要逆向循环序列的话,先正向定位序列,然后调用 reversed() 函数:
>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1
要按排序后的顺序循环序列的话,使用 sorted() 函数,它不改动原序列,而是生成一个新的已排序的序列:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear
相关文章
- pqdm 是 tqdm 和 concurrent.futures 的 wrapper | 一个小而美的 Python 并行计算库 | 实现多进程显示进度条的优雅方案
- Python 2D列表转1D列表的常见方法汇总
- Python中将字典转换为有序列表、无序列表的方法
- python中星号的意义(**字典,*列表或元组)
- 【Python】Padas DataFrame和列表List相互转换
- Python基础知识(二):序列结构---字符串、 列表、 元组、 字典、 集合
- python学习第八讲,python中的数据类型,列表,元祖,字典,之字典使用与介绍
- python学习第六讲,python中的数据类型,列表,元祖,字典,之列表使用与介绍
- Python之路迭代器协议、for循环机制、三元运算、列表解析式、生成器
- python的方向_Python有哪些就业方向
- Python 列表、元组、字典及集合操作详解
- Python 列表list 字典dict
- Python小练习:列表的相关操作
- 【Python基础】列表的基本操作:列表的数据统计、排序、遍历 || 关键字、函数、方法 || 列表的应用场景 || 元组的定义、循环遍历、应用场景 || 格式化字符 || 元组和列表之间的转换
- 【Python】集合生成式、【列表、字典、元组、集合】 小总结
- Python学习笔记之 高级变量类型 列表,元组,字典,字符串的相关常用 操作
- Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
- PyQt(Python+Qt)学习随笔:model/view架构中支持QListView列表中展示图标的两种方法
- Python中的列表解析和列表推导是一回事吗?
- 第3.3节 强大的Python列表
- python 获得github代码库列表
- Python 列表、字典和集合推导式及生成器表达式
- Python 使用Lambda对list(列表)中指定格式字符串元素排序方法
- Python 通过all()判断列表(list)中所有元素是否都包含某个字符串(string)
- 2022年最新Python大数据之Python基础【五】(列表、字典和集合)
- 【Python】for/else、列表的创建、查询、删除、修改、排序、列表生成式
- python - 字典之间的格式转换参考
- python - list列表的sort方法,对字典和列表进行排序
- python 在列表,元组,字典变量前加*号