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 Python
list的解析功能很有用(简洁优雅的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)