# 非列表解析式写法
even =[]
for x in rang(10):
if x % 2 == 0:
even.append(x)
------------------------------
# 列表解析式写法
even = [x for x in range(10) if x%2 == 0]
以下例子返回值会是什么?
newlist = [print(i) for i in range(10)]
print(newlist)
newlist1 = [str(i) for i in range(10)]
print(newlist1)
输出结果:
0
1
2
3
4
5
6
7
8
9
[None, None, None, None, None, None, None, None, None, None]
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
print([i for i in range(20) if i%2 == 0 and i%3 == 0])
print([i for i in range(20) if i%2 == 0 if i%3 == 0])
输出结果
[0, 6, 12, 18]
[0, 6, 12, 18]
print([(x,y) for x in 'abc' for y in range(3)])
print([[x,y] for x in 'abc' for y in range(3)])
print([{
x,y} for x in 'abc' for y in range(3)])
输出结果:
[('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2), ('c', 0), ('c', 1), ('c', 2)]
[['a', 0], ['a', 1], ['a', 2], ['b', 0], ['b', 1], ['b', 2], ['c', 0], ['c', 1], ['c', 2]]
[{
0, 'a'}, {
1, 'a'}, {
2, 'a'}, {
0, 'b'}, {
1, 'b'}, {
2, 'b'}, {
0, 'c'}, {
1, 'c'}, {
2, 'c'}]
请问下面3中输出各是什么?
print([(x,y) for x in range(7) if x >4 for y in range(20,25) if y>23])
print([(x,y) for x in range(7) for y in range(20,25)if x>4 if y>23])
print([(x,y) for x in range(7) for y in range(20,25)if x>4 and y>23])
输出结果
[(5, 24), (6, 24)]
[(5, 24), (6, 24)]
[(5, 24), (6, 24)]
g =("{:04}".format(i) for i in range(1,5))
next(g)
for x in g:
print(x)
print('-----------')
for x in g:
print(x)
输出结果
0002
0003
0004
-----------
解析:1.延迟计算;2.返回迭代器,可以迭代;3.从前到后走完一遍后,不能回头
g =["{:04}".format(i) for i in range(1,5)]
for x in g:
print(x)
print('-----------')
for x in g:
print(x)
0001
0002
0003
0004
-----------
0001
0002
0003
0004
{(x, x+1) for x in range(10)}
注: {[x] for x in range(10)},会报TypeError错误,因为[x]是list,集合内的元素需要可hash,而list是不可hash
{x:(x,x+1) for x in range(5)}
{x:[x,x+1] for x in range(5)}
{(x,):[x,x+1] for x in range(5)}
注:{[x]:[x,x+1] for x in range(5)},会报TypeError错误,因为key是list,不可hash
{str(x):y for x in range(3) for y in range(4)} 会输出几个元素呢?
输出结果: {‘0’:3, ‘1’:3, ‘2’:3} 原因是字典有去重特性,而后一次的输出结果会覆盖前一次。
第一题 使用列表解析式 打印九九乘法表 第一题
第二题 使用列表解析式生成 “0001.abadicddws” 格式的ID号 第一题
要求ID格式是以点号分割,左边是4位从1开始的整数,右边是10位随机小写英文字母。
请依次生成前100个ID的列表,如图:
'0001.bbcomlkdyt'
'0002.yzjudytpna'
'0003.zycscjsvfy'
'0004.hhvqzlukui'
'0005.xissuxwsou'
习题参考答案