Python使用for生成列表實現過程解析
在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’]
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
