列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。
例子,要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11))
list(range(1,11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list(range(12))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
#生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?
L = []
for x in range(1, 11):
L.append(x * x)
L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
l = [1,2,3,4,5,6]
def pfhanshu(n):
newList = []
for item in list(range(1,n+1)):
pingfang = item*item
#print(pingfang)
newList.append(pingfang)
return newList
pfhanshu(15)
# def abc():
# for item in l:
# return item
# abc()
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225]
#列表生成式则可以用一行语句代替循环生成上面的list:
# [x * x for x in range(1, 11)]
[item*item for item in range(1,17)]
#列表生成式的写法
#[ 要循环的每一项的应该做的操作 for item in range(20,101) if 条件判断表达式]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256]
#[1,2,3,4,5]===》['这是第1项','这是第2项','这是第3项']
[ '这是第%s项'%item for item in range(1,6) if item>=3 ]
['这是第3项', '这是第4项', '这是第5项']
#for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方:
[x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
#列出当前目录下的所有文件和目录名,可以通过一行代码实现:
import os # 导入os模块,模块的概念后面讲到
[d for d in os.listdir('./')] # os.listdir可以列出文件和目录
['.ipynb_checkpoints', '切片.ipynb', '列表生成式.ipynb', '迭代.ipynb']
import os
[item for item in os.listdir('./') if len(item)>8 ]
['.ipynb_checkpoints', '列表生成式.ipynb', '生成器.ipynb', '迭代器.ipynb']
#for循环其实可以同时使用两个甚至多个变量,比如dict的items()可以同时迭代key和value:
d = {'x': 'A', 'y': 'B', 'z': 'C' }
for k, v in d.items():
print(k, '=', v)
x = A y = B z = C
#列表生成式也可以使用两个变量来生成list:
d = {'x': 'A', 'y': 'B', 'z': 'C' }
[k + '=' + v for k, v in d.items()]
['x=A', 'y=B', 'z=C']
#list中所有的字符串变成小写:
L = ['Hello', 'World', 'IBM', 'Apple']
[s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']
student = {
'name':'小王',
'sex':'man',
'studentNumber':88888
}
for item in student:
print(item,":",student[item])
name : 小王 sex : man studentNumber : 88888
for key,value in student.items():
print(key,":",value)
name : 小王 sex : man studentNumber : 88888
studentName=['小明','小黑','小白']
number = 0
for item in studentName:
number = number+1
if number>2 :
break
else:
print(item)
小明 小黑
for (index,value) in enumerate(studentName):
print(index)
print(value)
print(studentName[index])
0 小明 小明 1 小黑 小黑 2 小白 小白
students = [
{'name':'xiaoming'},
{'name':'xiaohong'},
{'name':'xiaohei'}
]
enumerate
for i,value in enumerate(students):
print(i,value)
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'helloWorld'
app.run(debug=True)
0 {'name': 'xiaoming'} 1 {'name': 'xiaohong'} 2 {'name': 'xiaohei'}
--------------------------------------------------------------------------- UnsupportedOperation Traceback (most recent call last) <ipython-input-6-9ce71dbdac1c> in <module>() 19 return 'helloWorld' 20 ---> 21 app.run(debug=True) 22 C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py in run(self, host, port, debug, load_dotenv, **options) 936 options.setdefault('threaded', True) 937 --> 938 cli.show_server_banner(self.env, self.debug, self.name, False) 939 940 from werkzeug.serving import run_simple C:\ProgramData\Anaconda3\lib\site-packages\flask\cli.py in show_server_banner(env, debug, app_import_path, eager_loading) 627 message += ' (lazy loading)' 628 --> 629 click.echo(message) 630 631 click.echo(' * Environment: {0}'.format(env)) C:\ProgramData\Anaconda3\lib\site-packages\click\utils.py in echo(message, file, nl, err, color) 257 258 if message: --> 259 file.write(message) 260 file.flush() 261 UnsupportedOperation: not writable
x,y = yuanzu
print(x)
print(y)
23 46