Python列表推导式的使用方法
时间:2023-05-10 07:01:46
1.列表推导式书写形式:
[表达式 for 变量 in 列表] 或者 [表达式 for 变量 in 列表 if 条件]
2.举例说明:
#!/usr/bin/python
# -*- coding: utf-8 -*-
li = [1,2,3,4,5,6,7,8,9]
print [x**2 for x in li]
print [x**2 for x in li if x>5]
print dict([(x,x*10) for x in li])
print [ (x, y) for x in range(10) if x % 2 if x > 3 for y in range(10) if y > 7 if y != 8 ]
vec=[2,4,6]
vec2=[4,3,-9]
sq = [vec[i]+vec2[i] for i in range(len(vec))]
print sq
print [x*y for x in [1,2,3] for y in [1,2,3]]
testList = [1,2,3,4]
def mul2(x):
return x*2
print [mul2(i) for i in testList]
结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[36, 49, 64, 81]
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90}
[(5, 9), (7, 9), (9, 9)]
[6, 7, -3]
[1, 2, 3, 2, 4, 6, 3, 6, 9]
[2, 4, 6, 8]
3.总结:
我觉得就是通过for 语句处理表达式里面的变量,如果还要加条件,就加if条件就可以了。
标签:列表推导式,Python
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用Pycharm创建一个Django项目的超详细图文教程
2021-07-13 10:47:17
![](https://img.aspxhome.com/file/2023/7/117987_0s.jpg)
Mysql的慢SQL优化思路和规范详解
2024-01-22 22:01:15
![](https://img.aspxhome.com/file/2023/1/97571_0s.webp)
escape,encodeURI,encodeURIComponent函数比较
2008-01-27 11:19:00
python 实现简易的记事本
2022-10-17 18:24:21
![](https://img.aspxhome.com/file/2023/3/133313_0s.png)
flask中过滤器的使用详解
2023-03-01 16:00:55
详解Python数据类型、进制转换、字符串格式化的问题
2022-11-11 16:24:10
![](https://img.aspxhome.com/file/2023/9/133359_0s.jpg)
python 输出列表元素实例(以空格/逗号为分隔符)
2023-10-03 16:40:52
利用Python实现Shp格式向GeoJSON的转换方法
2021-01-30 09:14:49
![](https://img.aspxhome.com/file/2023/1/121391_0s.jpg)
js前端实现登录拼图验证功能
2024-04-19 10:45:29
![](https://img.aspxhome.com/file/2023/9/135779_0s.jpg)
10 个Python中Pip的使用技巧分享
2023-08-02 17:52:45
Vue3兄弟组件传值之mitt的超详细讲解
2023-07-02 16:56:04
用Python实现屏幕截图详解
2022-01-30 08:00:19
简单的Vue SSR的示例代码
2023-07-02 17:08:46
![](https://img.aspxhome.com/file/2023/9/139949_0s.jpg)
Python 如何求矩阵的逆
2021-07-22 23:28:43
![](https://img.aspxhome.com/file/2023/7/72807_0s.jpg)
ODBC连接数据库以SQLserver为例图文详解
2024-01-13 04:07:43
![](https://img.aspxhome.com/file/2023/6/122366_0s.png)
PHP二维码的生成与识别案例
2023-06-14 06:48:55
![](https://img.aspxhome.com/file/2023/2/55562_0s.png)
Bootstrap导航栏各元素操作方法(表单、按钮、文本)
2023-08-15 05:14:27
![](https://img.aspxhome.com/file/2023/3/56083_0s.png)
从"..."看中国的UI设计界的粗糙
2007-11-21 19:28:00
![](https://img.aspxhome.com/file/UploadPic/200711/21/20071121193134977s.gif)
Python读取二进制文件代码方法解析
2023-06-14 14:32:35
python 通过logging写入日志到文件和控制台的实例
2021-04-26 00:04:38