后台-插件-广告管理-内容页广告位一(手机)

# python基础（补充）：列表推导式

2021-04-18 18:37:02python人已围观

# 带有单循环的推导式

``````print( list(range(1, 11)))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
``````

``````li = []
for i in range(1, 11):
li.append(i * i)

print(li)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
``````

``````print([x * x for x in range(1, 11)])
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
``````

# 带有判断条件的单循环推导式

## if

for循环后面还可以加上if判断，这样我们就可以筛选出仅偶数的平方：

``````print([x * x for x in range(1, 11) if x % 2 == 0])
# [4, 16, 36, 64, 100]
``````

``````print([x for x in range(1, 11) if x % 2 == 0 else 0])

'''
File "D:/python_project/mxxl/test/test.py", line 1
print([x for x in range(1, 11) if x % 2 == 0 else 0])
^
SyntaxError: invalid syntax

'''
``````

## if...else

``````[x if x % 2 == 0 for x in range(1, 11)]

'''
File "D:/python_project/mxxl/test/test.py", line 1
[x if x % 2 == 0 for x in range(1, 11)]
^
SyntaxError: invalid syntax

'''
``````

``````print([x if x % 2 == 0 else -x for x in range(1, 11)])
# [-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
``````

# 带有多循环的推导式

``````print([m + n for m in 'ABC' for n in 'XYZ'])
# [m + n for m in 'ABC' for n in 'XYZ']
``````

``````d = {'x': 'A', 'y': 'B', 'z': 'C' }
for k, v in d.items():
print(k, '=', v)

# x = A
# y = B
# z = C
``````

``````d = {'x': 'A', 'y': 'B', 'z': 'C' }
print([k + '=' + v for k, v in d.items()])

# ['x=A', 'y=B', 'z=C']
``````

# 带有判断条件的多循环推导式

``````li1 = ['1','2','3']
li2 = ['a','b','c']
li = [i + "=" + j for i in li1 for j in li2 if li1.index(i) == li2.index(j)]
print(li)

# ['1=a', '2=b', '3=c']
``````

Tags：推导   补充   基础   列表   python

 后台-插件-广告管理-内容页广告位二(手机)

## 相关文章

 后台-插件-广告管理-内容页广告位三(手机)
 后台-插件-广告管理-内容页广告位四(手机)

## 文章评论

 留言与评论（共有 0 条评论）

 验证码：

## 站点信息

• 文章统计13614篇文章
• 浏览统计468次浏览
• 评论统计1个评论
• 标签管理标签云
• 统计数据：统计代码
• 微信公众号：扫描二维码，关注我们