Python基础学习笔记3 - list 和 str 的区别,转化,list解析

来源:互联网 发布:淘宝品牌的市场定位 编辑:程序博客网 时间:2024/06/06 03:22

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 testListteststr='Hello, I like Python'testList=teststr.split(',')print testList
分别返回:['Hello', 'I', 'like', 'Python']
['Hello', ' I like Python']
split(...) S.split([sep [,maxsplit]]) -> list of stringsReturn a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splitsare done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed fromthe 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)

0 0
原创粉丝点击