JackLi07

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.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.列表的删操作(四种)

  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. 

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.

posted @ 2018-10-25 20:26  JackLi07  阅读(204)  评论(0编辑  收藏  举报