如果你想要函数的调用者在某个参数位置只能使用位置参数而不能使用关键字参数传参,那么你只需要在所需位置后面放置一个/。
list(iterable=(), /)
# 常用的方法有
l = list(range(10)) # 通过range迭代生成list
l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l.append(100) # 在list最后添加元素
l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]
l.extend([101]) # 在list后通过迭代(iterable)添加元素
l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 101]
### 注意区分append()和extend() ###
l.insert(3, 102) # 在指定位置添加元素(加在指定位置的元素之前)
l
[0, 1, 2, 102, 3, 4, 5, 6, 7, 8, 9, 100, 101]
l.insert(-2, 103) # 对比利用负index的添加元素(也是加在指定位置之前,若要加在最后,则使用append())
l
[0, 1, 2, 102, 3, 4, 5, 6, 7, 8, 9, 103, 100, 101]
l.pop() # 删除某个元素(默认是最后一个)
101
l
[0, 1, 2, 102, 3, 4, 5, 6, 7, 8, 9, 103, 100]
l.pop(3) # 删除第4个元素
102
l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 103, 100]
l_copy = l.copy() # copy()提供一个浅拷贝
l_copy
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 103, 100]
l_copy.remove(103) # 移除对应值的元素,若不存在该值的元素则返回ValueError,说明该值不在该list中
l_copy
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]
l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 103, 100]
l_copy.sort() # 排序,默认升序,提供reverse=True参数时,则为降序
l_copy
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]
def func(x):
return x*(x-10)
l_copy.sort(key=func) # 对list中的每个元素应用关键方法,之后利用获得的值进行排序
l_copy
[5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 100]
l_copy.reverse() # 逆序
l_copy
[100, 0, 9, 1, 8, 2, 7, 3, 6, 4, 5]
l_copy.clear() # 清除所有元素,使得list变为空列表
l_copy
[]
原文:https://www.cnblogs.com/musicalife/p/14675444.html