Python使用for生成列表實(shí)現(xiàn)過(guò)程解析
在python中,可以把for循環(huán)寫(xiě)在一行,生成一個(gè)新的列表,使用起來(lái)非常方便,下面舉幾個(gè)簡(jiǎn)單例子體會(huì)一下。
1.簡(jiǎn)單的for...[if]...語(yǔ)句
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.把兩個(gè)列表進(jìn)行某種處理生成新列表
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’]
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Android table布局開(kāi)發(fā)實(shí)現(xiàn)簡(jiǎn)單計(jì)算器2. IntelliJ IDEA安裝插件的方法步驟3. 理解PHP5中static和const關(guān)鍵字4. php模擬實(shí)現(xiàn)斗地主發(fā)牌5. spring acegi security 1.0.0 發(fā)布6. MyBatis中的JdbcType映射使用詳解7. vue 使用localstorage實(shí)現(xiàn)面包屑的操作8. Python random庫(kù)使用方法及異常處理方案9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備