Python:List用法与示例速查整理

相关资料地址:gto76/python-cheatsheet: Comprehensive Python Cheatsheet (github.com)


目录

一、List 切片

1、索引切片示例

2、步进切片示例

二、List 添加元素

1、append 的用法示例

2、extend 的用法示例

三、List的排序

1、sort的用法示例

2、sorted的用法示例

3、reverse的用法示例

4、reversed的用法示例

四、List的增删查改

1、List的插入

2、List的元素删除

(1)pop的用法示例(根据index删除)

(2)remove的用法示例(根据value删除)

(3)clear的用法示例(删除所有元素) 

3、List的查询

(1)count的用法示例(查询元素在列表中的数量)

(2)index的用法示例(查询元素在列表中的index)

五、List的一些其他常用用法与示例

1、sum的用法示例(整型类列表相加)

2、sorted的常见用法

3、itertools.chain.from_iterable的用法示例(将多个迭代器连接成一个统一的迭代器)

4、list对reduce的用法示例(reduce会对list中元素按func进行累积)

5、通过List获取字符串的每一个字符


一、List 切片

用法:

 = []       # Or: [from_inclusive : to_exclusive : ±step]

示例:

1、索引切片示例

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 切片切法应用1
new_list = my_list[2::]
# [3, 4, 5, 6, 7, 8, 9]


# 切片切法应用2
new_list = my_list[:5:]
# [1, 2, 3, 4, 5]


# 切片切法应用3
new_list = my_list[2:5:]
# [3, 4, 5]


# 切片切法应用4
new_list = my_list[-5::]
# [5, 6, 7, 8, 9]


# 切片切法应用5
new_list = my_list[:-2:]
# [1, 2, 3, 4, 5, 6, 7]


# 切片切法应用6
new_list = my_list[-5:-2:]
# [5, 6, 7]

2、步进切片示例

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 切片步进应用1:倒序 
new_list = my_list[::-1]
# [9, 8, 7, 6, 5, 4, 3, 2, 1]


# 切片步进应用2:固定间隔选取
new_list = my_list[::2]
# [1, 3, 5, 7, 9]


# 切片步进应用3
new_list = my_list[::-2]
# [9, 7, 5, 3, 1]

二、List 添加元素

用法:

.append()            # Or:  += []
.extend()    # Or:  += 

示例:

1、append 的用法示例

# .append()            # Or:  += []
my_list = []

# 元素的添加1
my_list.append(1)
# [1]


# 元素的添加2
testList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
testList1 = [10, 11, 12]
testTuple = (0, 1)
testTuple1 = (2, 3)

my_list.append(testList)
my_list.append(testList1)
my_list.append(testTuple)
my_list.append(testTuple1)
# [[1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12], (0, 1), (2, 3)]

2、extend 的用法示例

# .extend()    # Or:  += 
# extend的用法:将目标集合中的每个元素放置list中

my_list = []

# 用法示例1
testList = [1, 2]
testList1 = [3, 4]
testTuple = (5, 6)
testTuple1 = (7, 8)

my_list.extend(testList)
my_list.extend(testList1)
my_list.extend(testTuple)
my_list.extend(testTuple1)
# [1, 2, 3, 4, 5, 6, 7, 8]

三、List的排序

用法:

.sort()                  # Sorts in ascending order.
.reverse()               # Reverses the list in-place.
 = sorted()  # Returns a new sorted list.
 = reversed()      # Returns reversed iterator.

示例:

1、sort的用法示例

# .sort()                  # Sorts in ascending order.

# sort:默认升序排序
my_list = [6, 7, 8, 9 ,1, 2, 3, 4, 5]
my_list.sort()
# [1, 2, 3, 4, 5, 6, 7, 8, 9]


# sort:降序排序
my_list = [6, 7, 8, 9 ,1, 2, 3, 4, 5]
my_list.sort(reverse=True)
# [9, 8, 7, 6, 5, 4, 3, 2, 1]


# sort:字符按照ASCII码进行排序
my_list = ['e', 'f', 'g','a', 'b', 'c', 'A']
my_list.sort()
# ['A', 'a', 'b', 'c', 'e', 'f', 'g']

# sort:用指定的方法进行排序
# 名字长度升序/降序排序
def myFunc(element):
    return len(element)
my_list = ['Porsche', 'Audi', 'BMW', 'Volvo']
my_list.sort(key=myFunc)
# ['BMW', 'Audi', 'Volvo', 'Porsche']
my_list.sort(key=myFunc, reverse=True)
# ['Porsche', 'Volvo', 'Audi', 'BMW']

2、sorted的用法示例

#  = sorted()  # Returns a new sorted list.

# Sorted 的用法:将可迭代的对象元素转成列表
# Sorted 的排序方法与sort一致
my_list = [6, 7, 8, 9 ,1, 2, 3, 4, 5]
new_list = sorted(my_list)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

my_tuple = (5, 2, 1, 3, 4)
new_list = sorted(my_tuple)
# [1, 2, 3, 4, 5]

my_dict = {4:'a', 5:'b', 3:'c',  2:'d', 1:'e'}
new_list = sorted(my_dict.items())
# [(1, 'e'), (2, 'd'), (3, 'c'), (4, 'a'), (5, 'b')]


# sorted:用指定的方法进行排序
# 名字长度升序/降序排序
def myFunc(element):
    return len(element)
my_list = ['Porsche', 'Audi', 'BMW', 'Volvo']
new_list = sorted(my_list, key=myFunc)
# ['BMW', 'Audi', 'Volvo', 'Porsche']

new_list = sorted(my_list, key=myFunc, reverse=True)
# ['Porsche', 'Volvo', 'Audi', 'BMW']

3、reverse的用法示例

# .reverse()               # Reverses the list in-place.

# reverse: 将列表按反向排列
my_list = [6, 7, 8, 9 ,1, 2, 3, 4, 5]
my_list.reverse()
# [5, 4, 3, 2, 1, 9, 8, 7, 6]

4、reversed的用法示例

#  = reversed()      # Returns reversed iterator.

# reversed:返回一个逆序的迭代器
my_list = [6, 7, 8, 9 ,1, 2, 3, 4, 5]
my_tuple = (4, 3, 2, 1, 5)

new_iterator = reversed(my_list)
# 

new_iterator1 = reversed(my_tuple)
# 

new_list = list(new_iterator)
# [5, 4, 3, 2, 1, 9, 8, 7, 6]

new_tuple = tuple(new_iterator1)
# (5, 1, 2, 3, 4)

四、List的增删查改

用法:

.insert(, )     # Inserts item at index and moves the rest to the right.
  = .pop([])    # Removes and returns item at index or from the end.
 = .count()     # Returns number of occurrences. Also works on strings.
 = .index()     # Returns index of the first occurrence or raises ValueError.
.remove()            # Removes first occurrence of the item or raises ValueError.
.clear()                 # Removes all items. Also works on dictionary and set.

示例:

1、List的插入

# .insert(, )     # Inserts item at index and moves the rest to the right.

# list的元素插入
my_list = ['a', 'b', 'c', 'd']
my_list.insert(1, 'abcde')
# ['a', 'abcde', 'b', 'c', 'd']

2、List的元素删除

(1)pop的用法示例(根据index删除)

  • 报错类型:IndexError
#   = .pop([])    # Removes and returns item at index or from the end.
# pop:根据index来删除list元素

# list的元素删除1
my_list = ['a', 'b', 'c', 'd']
el = my_list.pop()
# d
# ['a', 'b', 'c']

# list的元素删除2
my_list = ['a', 'b', 'c', 'd']
el = my_list.pop(1)
# b
# ['a', 'c', 'd']

# list的元素删除3
my_list = ['a', 'b', 'c', 'd']
el = my_list.pop(7)
# IndexError: pop index out of range

(2)remove的用法示例(根据value删除)

  • 报错类型:ValueError
# .remove()            # Removes first occurrence of the item or raises ValueError.

# list的元素删除1
my_list = ['a', 'b', 'c', 'd']
my_list.remove('b')
# ['a', 'c', 'd']


# list的元素删除2
my_list = ['a', 'b', 'c', 'd']
my_list.remove('e')
# ValueError: list.remove(x): x not in list

(3)clear的用法示例(删除所有元素) 

# .clear()                 # Removes all items. Also works on dictionary and set.

# list所有元素的删除
my_list = ['a', 'b', 'c', 'd']
my_list.clear()
# []

3、List的查询

(1)count的用法示例(查询元素在列表中的数量)

#  = .count()     # Returns number of occurrences. Also works on strings.

# count的用法1
my_list = ['a', 'a', 'b', 'c', 'd']
count = my_list.count('a')
# 2


# count的用法2
my_list = ['a', 'a', 'b', 'c', 'd']
count = my_list.count('f')
# 0

(2)index的用法示例(查询元素在列表中的index)

  • 报错类型:ValueError
#  = .index()     # Returns index of the first occurrence or raises ValueError.

# index的用法1
my_list = ['a', 'b', 'c', 'd']
my_index = my_list.index('c')
# 2


# index的用法2
my_list = ['a', 'b', 'c', 'd']
my_index = my_list.index('f')
# ValueError: 'f' is not in list

五、List的一些其他常用用法与示例

用法:

sum_of_elements  = sum()
elementwise_sum  = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(, key=lambda el: el[1])
sorted_by_both   = sorted(, key=lambda el: (el[1], el[0]))
flatter_list     = list(itertools.chain.from_iterable())
product_of_elems = functools.reduce(lambda out, el: out * el, )
list_of_chars    = list()

示例:

1、sum的用法示例(整型类列表相加)

  • 报错类型:TypeError
# sum_of_elements  = sum()
# elementwise_sum  = [sum(pair) for pair in zip(list_a, list_b)]

# sum的用法1
my_list = [2, 4, 6, 3]
my_sum = sum(my_list)
# 15

# sum的用法2
my_list = ['a', 'b', 'c', 'd']
my_sum = sum(my_list)
# TypeError: unsupported operand type(s) for +: 'int' and 'str'


# sum的用法3
my_list = [2, 4, 6, 3]
my_list1 = [3, 6, 4, 2]
elementwise_sum  = [sum(x) for x in zip(my_list, my_list1)]
# [5, 10, 10, 5]


# sum的用法4
my_list = ['a', 'b', 'c', 'd']
my_list1 = [3, 6, 4, 2]
elementwise_sum  = [sum(x) for x in zip(my_list, my_list1)]
# TypeError: unsupported operand type(s) for +: 'int' and 'str'

2、sorted的常见用法

# sorted_by_second = sorted(, key=lambda el: el[1])
# sorted_by_both   = sorted(, key=lambda el: (el[1], el[0]))


# sorted常见用法1
dict = {0:'a', 1:'e', 2:'c', 4:'f', 3:'b'}
new_list = sorted(dict.items(), key= lambda x : x[1])
# [(0, 'a'), (3, 'b'), (2, 'c'), (1, 'e'), (4, 'f')]

# sorted常见用法2
dict = {0:'a', 1:'e', 2:'c', 4:'f', 3:'b'}
new_list = sorted(dict.items(), key= lambda x :(x[0], x[1]))
# [(0, 'a'), (1, 'e'), (2, 'c'), (3, 'b'), (4, 'f')]

3、itertools.chain.from_iterable的用法示例(将多个迭代器连接成一个统一的迭代器)

# flatter_list     = list(itertools.chain.from_iterable())

import itertools

my_dict = {0:'a', 1:'e', 2:'c', 4:'f', 3:'b'}
new_list = list(itertools.chain.from_iterable(my_dict.values()))
# ['a', 'e', 'c', 'f', 'b']

new_list = list(itertools.chain.from_iterable(my_dict.items()))
# [0, 'a', 1, 'e', 2, 'c', 4, 'f', 3, 'b']

4、list对reduce的用法示例(reduce会对list中元素按func进行累积)

# product_of_elems = functools.reduce(lambda out, el: out * el, )

import functools

# reduce对list的使用方法1
my_list = [2, 4, 6, 3]
new_ele = functools.reduce(lambda x, y: x+y, my_list)
# 15


# reduce对list的使用方法2
my_list = ['a', 'b', 'c', 'd']
new_ele = functools.reduce(lambda x, y: x+y, my_list)
# abcd


# reduce对list的使用方法3
def myFunc(x, y):
    return str(x) + str(y)
my_list = ['a', 'b', 1, 2]
new_ele = functools.reduce(myFunc, my_list)
# ab12

5、通过List获取字符串的每一个字符

# list_of_chars    = list()

# 用List获取字符串的每一个字符
myStr = 'hello world!'
my_list = list(myStr)
# ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']

你可能感兴趣的:(Python,Python,list,collections)