Python使用for生成列表實(shí)現(xiàn)過程解析
在python中,可以把for循環(huán)寫在一行,生成一個(gè)新的列表,使用起來非常方便,下面舉幾個(gè)簡單例子體會(huì)一下。
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.把兩個(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’]
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼2. 如何在PHP中讀寫文件3. java加載屬性配置properties文件的方法4. PHP正則表達(dá)式函數(shù)preg_replace用法實(shí)例分析5. 什么是Python變量作用域6. 《Java程序員修煉之道》作者Ben Evans:保守的設(shè)計(jì)思想是Java的最大優(yōu)勢(shì)7. CSS3中Transition屬性詳解以及示例分享8. php redis setnx分布式鎖簡單原理解析9. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼10. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式
