(三)列表<1>基础

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

1.数字和数据是有区别的,数据可能是文字,图片等.

2.列表是可以用bool()判断真假的:

>>> a=[]
>>> bool(a)
False
>>> a=[1,2,3]
>>> bool(a)
True
>>> 

3.列表是Python的苦力,啥活都干---不只局限于一种对象,可以包含各种对象.

4.序列的切片,左边的数字一定小于右边的数字:

>>> lang='Python'
>>> lang[-1]
'n'
>>> lang[-3]
'h'
>>> lang[-1,-3]
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    lang[-1,-3]
TypeError: string indices must be integers
>>> lang[-3:-1] #只包含到-2的元素
'ho'
# 二次切片,不要奇怪这种形式
>>> list1=[1,2,'www.sina.com']
>>> list1[2][4:8]
'sina'

5.列表的"反转"

>>> list1=[1,2,3,4,5,6]
>>> list1[:]
[1, 2, 3, 4, 5, 6]
>>> list1[::]
[1, 2, 3, 4, 5, 6]
>>> list1[:::]
SyntaxError: invalid syntax
>>> list1[::-1]
[6, 5, 4, 3, 2, 1] #反转
>>> list1 #可见,反转是生成一个新的对象
[1, 2, 3, 4, 5, 6]
>>> reversed(list1)
<list_reverseiterator object at 0x000000000312ECC0>
>>> list(reversed(list1))
[6, 5, 4, 3, 2, 1]
>>> list1
[1, 2, 3, 4, 5, 6]

6.末尾追加元素的两种方法---append和list1[len(list1):]

>>> list1=["I","like","Python"]
>>> list1[len(list1):]="very much" #如果是str对象,则是拆分的
>>> list1
['I', 'like', 'Python', 'v', 'e', 'r', 'y', ' ', 'm', 'u', 'c', 'h']
>>> list1=["I","like","Python"]
>>> list1
['I', 'like', 'Python']
>>> list1[len(list1):]=["very much"] #如果是list对象,则是一起的
>>> list1
['I', 'like', 'Python', 'very much']
>>> list1.append("very very much")
>>> list1
['I', 'like', 'Python', 'very much', 'very very much']

--------------------------------------------------------补充:
1.index不是内建函数,str有,list也有,类似,不一样

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

index(...)
    S.index(sub[, start[, end]]) -> int
    
    Like S.find() but raise ValueError when the substring is not found.

>>> help(list.index)
Help on method_descriptor:

index(...)
    L.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.
上一篇 下一篇

猜你喜欢

热点阅读