创建一个list数据的
>>> list(range(1,11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
python真的是很脑洞,这种写法都有
>>> [x * x for x in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[自变量表达式 for 自变量 in range(范围)]
上述的格式的 for 循环加判断
>>> [x * x for x in range(1,11) if (x %2 == 0)]
[4, 16, 36, 64, 100]
>>>
[自变量表达式 for 自变量 in range(范围) 条件判断]
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 列表生成式子
mList1 = [m for m in "ABC"]
print(mList1)
mList2 = [m for m in "ABC" for n in "XYZ"]
print(mList2)
mList3 = [m+n for m in "ABC" for n in "XYZ"]
print(mList3)
运行结果
D:\PythonProject>python Run.py
['A', 'B', 'C']
['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
从项目的角度来说,最多2次层的循环即可,不需要理解太多的逻辑。细节了解既可以,不需要一定掌握。
for循环同时放入2个变量
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# For循环生成列表-dict
mDict = {
"清朝":"康熙", "明朝":"朱元璋", "元朝":"成吉思汗"}
for key, value in mDict.items():
print(key, value)
运行结果
D:\PythonProject>python Run.py
清朝 康熙
明朝 朱元璋
元朝 成吉思汗
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 字符串列表大小写转换
mList = ["AAA", "BBB", "CCC"]
# 写法 1
mLowList = [s.lower() for s in mList]
print(mLowList)
# 写法 2
for s in mList:
print(s.lower())
运行结果
D:\PythonProject>python Run.py
['aaa', 'bbb', 'ccc']
aaa
bbb
ccc