(三)列表<3>回顾列表

2018-12-25  本文已影响0人  费云帆

1.多维列表

>>> list1=[1,[2,3,4],['a','b','c']]
# 看到这种格式不要惊奇...
>>> list1[2][2]
'c'

2.列表和字符串的转换(某些条件下成立):

>>> help(str.split)
Help on method_descriptor:

split(...)
    S.split(sep=None, maxsplit=-1) -> list of strings
    
    Return a list of the words in 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.
>>> text="Hello.I'm Jim Green.Welcome you."
# 以文本的"."作为分隔符---生成列表
>>> text.split('.')
['Hello', "I'm Jim Green", 'Welcome you', '']
# 可以看到,text指向的对象并没有发生改变
>>> text
"Hello.I'm Jim Green.Welcome you."
# 只分隔一次
>>> text.split('.',1)
['Hello', "I'm Jim Green.Welcome you."]
>>> text="I am,writing\npython\tbook on line"
>>> text
'I am,writing\npython\tbook on line'
>>> print(text)
I am,writing
python  book on line
>>> text.split()
# 以见到的任何分隔符分隔,这里是空格吗?
['I', 'am,writing', 'python', 'book', 'on', 'line']
>>> name=['Albert','Ainstain']
# 啥都没传入,故直接拼一起
>>> ''.join(name)
'AlbertAinstain'
>>> '.'.join(name)
'Albert.Ainstain'
>>> ' '.join(name)
'Albert Ainstain'
>>> text="I am,writing\npython\tbook on line"
>>> print(text)
I am,writing
python  book on line
>>> text.split()
['I', 'am,writing', 'python', 'book', 'on', 'line']
# 这里不是' '.join(text)
>>> ' '.join(text.split())
'I am,writing python book on line'
>>> a=[1,2,3,'a','b','c']
>>> '+'.join(a)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    '+'.join(a)
TypeError: sequence item 0: expected str instance, int found
>>> a=[1,2,3,4,5,6]
>>> '+'.join(a)
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    '+'.join(a)
TypeError: sequence item 0: expected str instance, int found
>>> a=['a','b','c']
>>> '+'.join(a)
'a+b+c'
>>> 
上一篇 下一篇

猜你喜欢

热点阅读