Python使用for生成列表实现过程解析
作者:Lee_1985 时间:2021-11-28 08:15:30
在python中,可以把for循环写在一行,生成一个新的列表,使用起来非常方便,下面举几个简单例子体会一下。
1.简单的for...[if]...语句
list1 = [1,2,3,4,5,6,7,8,9]
new_list = [x for x in list1 if x % 2 == 0]
print new_list
输出:
[2, 4, 6, 8]
2.把双层列表生成单层新列表
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = [x for temp_list in list1 for x in temp_list]
print new_list
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
3.把两个列表进行某种处理生成新列表
list1 = [1,2,3]
list2 = ['a', 'b', 'c']
new_list1 = [(x,y) for x in list2 for y in list1] #组合元组列表
print new_list1
new_list2 = ["%s%d"%(x,y) for x in list2 for y in list1] #字符串组合拼接
print new_list2
输出:
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]
['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
来源:https://blog.51cto.com/14207158/2531178
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
关于分页
Python使用matplotlib简单绘图示例
![](https://img.aspxhome.com/file/2023/2/62902_0s.jpg)
pyqt5蒙版遮罩mask,setmask的使用
![](https://img.aspxhome.com/file/2023/2/98862_0s.png)
Python时间序列缺失值的处理方法(日期缺失填充)
小型分页的设计
编写安全的SQL Server扩展存储过程
使用python绘制常用的图表
![](https://img.aspxhome.com/file/2023/1/94051_0s.jpg)
PHP Laravel门面的实现原理详解
python字典与json转换的方法总结
python删除特定文件的方法
golang 实现一个restful微服务的操作
在Internet Explorer中正确使用MSXML
python中xlwt模块的具体用法
![](https://img.aspxhome.com/file/2023/4/92324_0s.png)
oracle & mysql 多实例启动区别
Python实现基于标记的分水岭分割算法
![](https://img.aspxhome.com/file/2023/2/66012_0s.jpg)
python调用c++传递数组的实例
MySQL与PHP的基础与应用专题之创建数据库表
![](https://img.aspxhome.com/file/2023/2/110342_0s.png)
python 绘制国旗的示例
![](https://img.aspxhome.com/file/2023/9/80509_0s.png)
python使用openCV遍历文件夹里所有视频文件并保存成图片
![](https://img.aspxhome.com/file/2023/6/103186_0s.png)