python之列表操作

列表的增删改查及其他操作

1.列表的增操作(四种)

  1. append(object):append object to end,directly used on list
  2.  insert(index,object):insert object before index,directly used on list
  3. extend(iterable object):extend list by appending elements from the iterable,directly used on list
  4.  "+":拼接,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.列表的删操作(四种)

  1. remove(value):remove first occurrence of value, Raises ValueError if the value is not present.directly used on list
  2. 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
  3. del[start:end:step]:remove items chosen by index,directly used on list 
  4. 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]可以按照切片的格式修改多个,切片的部分规则如下

  1. 类似于replace(替换)方法,[ ]内选的值无论多少均删去,新修改的元素无论多少均插入list中
  2. 当新元素只是一个单独的字符串时,将字符串分解为单个字符后全部加入列表
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. 

猜你喜欢

转载自www.cnblogs.com/JackLi07/p/9852605.html