相关资料地址:gto76/python-cheatsheet: Comprehensive Python Cheatsheet (github.com)
目录
3、itertools.chain.from_iterable的用法示例(将多个迭代器连接成一个统一的迭代器)
4、list对reduce的用法示例(reduce会对list中元素按func进行累积)
一、List 切片
用法:
<list> = <list>[<slice>] # Or: <list>[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 添加元素
用法:
<list>.append(<el>) # Or: <list> += [<el>]
<list>.extend(<collection>) # Or: <list> += <collection>
示例:
1、append 的用法示例
# <list>.append(<el>) # Or: <list> += [<el>]
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 的用法示例
# <list>.extend(<collection>) # Or: <list> += <collection>
# 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的排序
用法:
<list>.sort() # Sorts in ascending order.
<list>.reverse() # Reverses the list in-place.
<list> = sorted(<collection>) # Returns a new sorted list.
<iter> = reversed(<list>) # Returns reversed iterator.
示例:
1、sort的用法示例
# <list>.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的用法示例
# <list> = sorted(<collection>) # 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的用法示例
# <list>.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的用法示例
# <iter> = reversed(<list>) # 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)
# <list_reverseiterator object at 0x000001C5E0787A30>
new_iterator1 = reversed(my_tuple)
# <reversed object at 0x0000022608D67A30>
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的增删查改
用法:
<list>.insert(<int>, <el>) # Inserts item at index and moves the rest to the right.
<el> = <list>.pop([<int>]) # Removes and returns item at index or from the end.
<int> = <list>.count(<el>) # Returns number of occurrences. Also works on strings.
<int> = <list>.index(<el>) # Returns index of the first occurrence or raises ValueError.
<list>.remove(<el>) # Removes first occurrence of the item or raises ValueError.
<list>.clear() # Removes all items. Also works on dictionary and set.
示例:
1、List的插入
# <list>.insert(<int>, <el>) # 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
# <el> = <list>.pop([<int>]) # 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
# <list>.remove(<el>) # 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的用法示例(删除所有元素)
# <list>.clear() # Removes all items. Also works on dictionary and set.
# list所有元素的删除
my_list = ['a', 'b', 'c', 'd']
my_list.clear()
# []
3、List的查询
(1)count的用法示例(查询元素在列表中的数量)
# <int> = <list>.count(<el>) # 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
# <int> = <list>.index(<el>) # 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(<collection>)
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
flatter_list = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, el: out * el, <collection>)
list_of_chars = list(<str>)
示例:
1、sum的用法示例(整型类列表相加)
- 报错类型:TypeError
# sum_of_elements = sum(<collection>)
# 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(<collection>, key=lambda el: el[1])
# sorted_by_both = sorted(<collection>, 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(<list>))
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, <collection>)
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(<str>)
# 用List获取字符串的每一个字符
myStr = 'hello world!'
my_list = list(myStr)
# ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']