python列表入门1
list:列表
list.append()给列表添加元素:
>>> li=["a","b","c"]
>>> li.append("d")
>>> print(li)
['a', 'b', 'c', 'd']
list1.extend(list2)扩展列表(给列表添加多个元素):
>>> li=["a","b","c"]
>>> li.extend(["d","e"])
>>> print(li)
['a', 'b', 'c', 'd', 'e']
list.insert()给列表插入元素:
>>> li=["a","b","c"]
>>> li.insert(2,"new")
>>> print(li)
['a', 'b', 'new', 'c']
list.remove()删除指定元素:
>>> li=["a","b","c"]
>>> li.remove("b")
>>> print(li)
['a', 'c']
del(list[index])删除指定元素:
>>> li=["a","b","c"]
>>> del(li[2])
>>> print(li)
['a', 'c']
del(list)删除指定列表
list.pop()取出列表中最后一个元素:
>>> li=["a","b","c","d","e"]
>>> li.pop()
'e'
>>> print(li)
['a', 'b', 'c', 'd']
list.pop(index)取出指定下标的元素:
>>> li=["a","b","c","d","e"]
>>> li.pop(3)
'd'
>>> print(li)
['a', 'b', 'c', 'e']
list.count()查找元素出现次数:
>>> li=[123,234,456]
>>> li*3
[123, 234, 456, 123, 234, 456, 123, 234, 456]
>>> li
[123, 234, 456]
>>> li*=3
>>> li
[123, 234, 456, 123, 234, 456, 123, 234, 456]
>>> li.count(123)
3
list.index() 使用:
>>> li=["a","b","c"]
>>> li*=3
>>> li
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
>>> li.index("a")
0
>>> li.index("a",2,5)
3
list.sort()数组排序,list.reverse()数组反向:
>>> li=[1,3,5,6,2,4,0,8,9]
>>> li.sort()
>>> li
[0, 1, 2, 3, 4, 5, 6, 8, 9]
>>> li.reserve()
结合使用:list.sprt(reverse=True)
in,not in使用:
>>> li=["a","b","c","d","e"]
>>> "a" in li
True
>>> "a" not in li
False
>>> li=["a",["b","c","d"],"e"]
>>> "b" in li
False
>>> "b" in li[1]
True
list方法查询:
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
list 拷贝:
>>> li1=["a","b","c","d","e"]
>>> li2=li1[:]
>>> li2
['a', 'b', 'c', 'd', 'e']
>>> li3=li1
>>> li3
['a', 'b', 'c', 'd', 'e']
>>> li1.pop()
'e'
>>> li1
['a', 'b', 'c', 'd']
>>> li2
['a', 'b', 'c', 'd', 'e']
>>> li3
['a', 'b', 'c', 'd']