Python使用for生成列表实现过程解析

(编辑:jimmy 日期: 2024/9/22 浏览:2)

在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']

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

一句话新闻

Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。