list 和 str 的區別,轉化,list解析
阿新 • • 發佈:2019-01-24
list 和 str 的最大區別是:
list是可變的,str是不可變的
e.g list.append('test) #這個是允許的
teststr='test'
teststr[1]='a'
返回TypeError: 'str' object does not support item assignment
區別2:list是多維的,
e.g
listMulti=[[1,2],[3,4]]
list和str的轉換:
teststr='Hello I like Python' testList=teststr.split() print testList teststr='Hello, I like Python' testList=teststr.split(',') print testList
分別返回:['Hello', 'I', 'like', 'Python']
['Hello', ' I like Python']
split(...) S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits
are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from
the result.
join是split的相反方法
jointest=''.join(teststr)
print jointest
返回: Hello, I like Pythonlist的解析功能很有用(簡潔優雅的Python): 求平方:
squares = [x**2 for x in range(1,10)]
print squares
返回:[1, 4, 9, 16, 25, 36, 49, 64, 81]求100以內能被3整除的數
aliquto = [n for n in range(1,100) if n%3==0]
print aliquto
return [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
更優的實現: range(3,100,3)