操作列表(python)
2022/3/19 11:29:57
本文主要是介绍操作列表(python),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
操作列表(python)
文章目录
- 操作列表(python)
- 遍历整个列表
- 深入研究循环
- 忘记缩进
遍历整个列表
需要对列表中的每个元素都执行相同的操作时,可使用python中的for循环
下面使用for循环来打印魔术师的所有名字:
>>> magicians = ['alice', 'david', 'carolina'] >>> for magician in magicians: >>> print(magician) alice david carolina
上述代码中定义一个for循环,这行代码让python从列表magicians中取出一个名字,并将其与变量magician相关联。最后,让python打印前面赋给magician的名字。
深入研究循环
编写for循环时,可以给依次与列表中每个值相关联的临时变量指定任意名称。然而,选择描述单个列表元素的有意义名称大有脾益。例如,对于小猫列表、小狗列表和一般性列表,像下面这样编写for循环的第一行代码时不错的选择:
for cat in cats: for dog in dogs: for item in list_of_items:
这些命名约定有助于你明白for煦暖中将每个元素执行的操作。使用单数和复数名称,可帮助你判断代码段处理的是单个列表元素还是整个列表。
忘记缩进
对于位于for语句后面且属于循环组成部分的代码行,一定要缩进。如果忘记缩进,python会提醒你:
>>> magicians = ['alice', 'david', 'carolian'] >>> for magician in magicians: >>> print(magician)
函数调用print()应缩进却没有缩进。python没找到期望缩进的代码块时,会让你知道哪行代码有问题:
File "magicians.py", line3 print(magician) IndentationError: expected an indented block
这篇关于操作列表(python)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python