第六章、Python資料型別(list列表)
阿新 • • 發佈:2021-11-10
列表(List)
python中用方括號 [ ] 表示一個list,方括號裡面可以是各種資料型別。
>>> a=[1,'q',True]
>>> type(a)
<type 'list'>
1)列表也有類似字串一樣的索引和切片,方法一樣
>>> a=[1,23,2]
>>> a[0]
1
>>> a.index(1)
0
2)反轉:字串倒過來。
反轉,不是在“原地”把原來的值倒過來,而是新生成了一個值,那個值跟原來的值相比,是倒過來了,原來的值還存在於變數中
反轉有兩種方式:
>>> a=[1,23,2]
>>> a[::-1] #方式一
[2, 23, 1]
>>>a
[1,23,2]
>>> list(reversed(a)) #方式二
[2, 23, 1]
3)基礎操作
>>> a.append("like") #增加列表元素,追加到尾部
>>> a
[1, 23, 2, 'like']
>>> b=['q', 'w']
>>> a.extend(b) #b中的所有元素加入到a中
>>> a
[1, 2, 3, 'q', 'w']
>>> b
['q', 'w']
>>> a = "python"
>>> hasattr(a,'__iter__')
False
>>>b = [1,2]
>>> hasattr(b,'__iter__')
True
#hasattr()判斷一個字串是否是可迭代的,是返回True,否返回False。其判斷本質就是看該型別中是否有__iter__函式。用dir()查詢整型、字串、列表中,誰有__iter__。
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',