對列表實現迭代
in [1]: l1 = [1,2,3,4,5]
in [2]: l2 =
in [3]: for i in l1:
...:
in [4]: print l2
[1, 4, 9, 16, 25]
使用列表生成式完成上面的操作
in [5]: l3 = [ i**2 for i in l1 ]
in [6]: print l3
[1, 4, 9, 16, 25]
列表生成式可直接輸出,用時要賦給變數,如下
in [7]: [ i**2 for i in l1 ] #直接平方
out[7]: [1, 4, 9, 16, 25]
in [8]: print l1 #列印l1結果沒有儲存
[1, 2, 3, 4, 5]
for迴圈後還可以加上if判斷,下面算出大於3數字的平方
in [9]: l4 = [ i**2 for i in l1 if i >=3 ]
in [10]: print l4
[9, 16, 25]
列表生成式問題 來自廖雪峰的官方**
l2 = ???
in [47]: l2 = [s for s in l1 if isinstance(s,str)]
in [48]: print (l2)
列表生成式問題 找出.log結尾的檔案
in [51]: import os
in [52]: os.listdir('/var/log')
out[52]:
['tallylog',
'lastlog',
'wtmp',
'ppp',
'audit',
.....略
in [53]: filelist1 = os.listdir('/var/log')
in [54]: str.
str.capitalize str.format str.isupper str.rfind str.startswith
str.center str.index str.join str.rindex str.strip
str.count str.isalnum str.ljust str.rjust str.swapcase
str.decode str.isalpha str.lower str.rpartition str.title
str.encode str.isdigit str.lstrip str.rsplit str.translate
str.endswith str.islower str.mro str.rstrip str.upper
str.expandtabs str.isspace str.partition str.split str.zfill
str.find str.istitle str.replace str.splitlines
in [54]: help(str.endswith)
help on method_descriptor:
endswith(...)
s.endswith(suffix[, start[, end]]) -> bool
return true if s ends with the specified suffix, false otherwise.
with optional start, test s beginning at that position.
with optional end, stop comparing s at that position.
suffix can also be a tuple of strings to try.
in [55]: s1 = 'boot.log'
in [56]: s1.endswith('.log')
out[56]: true
in [57]: s2 = 'btmp'
in [58]: s2.endswith('.log')
out[58]: false
in [59]: filelist2 = [i for i in filelist1 if i.endswith('.log')]
in [60]: print filelist2
['yum.log', 'boot.log']
python基礎 列表生成式
列表生成式即list comprehensions,是python內建的非常簡單卻強大的可以用來建立list的生成式。舉個例子,要生成list 1,2,3,4,5,6,7,8,9,10 可以用list range 1,11 list range 1,11 1,2,3,4,5,6,7,8,9,10 但...
Python 列表生成式
列表生成式即list comprehensions,是python內建的非常簡單卻強大的可以用來建立list的生成式。舉個例子,要生成list 1,2,3,4,5,6,7,8,9,10 可以用list range 1,11 list range 1,11 1,2,3,4,5,6,7,8,9,10 但...
python列表生成式
全都是重點!列表生成式即listcomprehensions,是python內建的非常簡單卻強大的可以用來建立list的生成式。舉個例子,要生成list 1,2,3,4,5,6,7,8,9,10 可以用range 1,11 range 1,11 1,2,3,4,5,6,7,8,9,10 但如果要生成...