python之列表操作
Posted modifying
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 # 1.append 2 a.append([9,8,7,6]) 3 print(a) 4 --[1, 2, 3, 4, 5, 6, [9, 8, 7, 6]] 5 6 # 2.insert 7 a.insert(7, 8) 8 print(a) 9 --[1, 2, 3, 4, 5, 6, [9, 8, 7, 6], 8] 10 11 # 3. extend 12 a.extend("zhang") 13 print(a) 14 --[1, 2, 3, 4, 5, 6, [9, 8, 7, 6], 8, ‘z‘, ‘h‘, ‘a‘, ‘n‘, ‘g‘] 15 16 # 4. + 17 a = a+[9] 18 print(a) 19 --[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.
以上是关于python之列表操作的主要内容,如果未能解决你的问题,请参考以下文章