python之列表操作
1.列表的增操作(四种)
- append(object):append object to end,directly used on list
- insert(index,object):insert object before index,directly used on list
- extend(iterable object):extend list by appending elements from the iterable,directly used on list
- "+":拼接,list1 + list2 = [each elements in list1 and list2]
# 1.append a.append([9,8,7,6]) print(a) --[1, 2, 3, 4, 5, 6, [9, 8, 7, 6]] # 2.insert a.insert(7, 8) print(a) --[1, 2, 3, 4, 5, 6, [9, 8, 7, 6], 8] # 3. extend a.extend("zhang") print(a) --[1, 2, 3, 4, 5, 6, [9, 8, 7, 6], 8, 'z', 'h', 'a', 'n', 'g'] # 4. + a = a+[9] print(a) --[1, 2, 3, 4, 5, 6, [9, 8, 7, 6], 8, 'z', 'h', 'a', 'n', 'g', 9]
2.列表的删操作(四种)
- remove(value):remove first occurrence of value, Raises ValueError if the value is not present.directly used on list
- pop(index):remove and return item at index (default last),Raises IndexError if list is empty or index is out of range.directly used on list
- del[start:end:step]:remove items chosen by index,directly used on list
- clear():remove all items from list
a = [1, 2, 3, 4, 5, 6, 7, 8, 9] # 1.remove a.remove(3) print(a) --[1, 2, 4, 5, 6, 7, 8, 9] # 2.pop s = a.pop(1) print(s) print(a) --2 --[1, 4, 5, 6, 7, 8, 9] # 3. del del a[0:4:2] print(a) --[4, 6, 7, 8, 9] # 4. clear a.clear() print(a) --[]
3.列表的改操作(两种)
直接利用 list[index] = object 修改,[index]可以按照切片的格式修改多个,切片的部分规则如下
- 类似于replace(替换)方法,[ ]内选的值无论多少均删去,新修改的元素无论多少均插入list中
- 当新元素只是一个单独的字符串时,将字符串分解为单个字符后全部加入列表
a = [1, 2, 3, 4, 5, 6, 7, 8, 9] a[1:2] = "1", "2", "3" print(a) --[1, '1', '2', '3', 3, 4, 5, 6, 7, 8, 9] a[1:3] = "1", "2", "3" print(a) --[1, '1', '2', '3', '3', 3, 4, 5, 6, 7, 8, 9] a[1:4] = "1", "2" print(a) --[1, '1', '2', '3', 3, 4, 5, 6, 7, 8, 9] a[1:2] = "come on" print(a) --[1, 'c', 'o', 'm', 'e', ' ', 'o', 'n', '2', '3', 3, 4, 5, 6, 7, 8, 9]
4.列表的查操作(两种)
- directly query with list[index]
- using for loop just like “for i in list ”,each i in loop is item in list.
5.count(value)
count(value):return number of occurrences of value
6.index(value)
return first index of value.Raises ValueError if the value is not present.
7.reverse()
reverse *IN PLACE*
8.sort(key=None, reverse=False)
stable sort *IN PLACE*, if reverse is True(default is False), sort from big to small.