python使用for生成列表,,在python中,可


在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_list1new_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‘]

python使用for生成列表

评论关闭