索引
list[start:end:step]
start 默认0
end 默认列表长度 及 len(list)
step 默认1
slice关键字 保存索引为变量
indexs=slice(start:end:step)
list[indexs]
删除多个
a = [9,5,2,3,7]
del a[:3] # 删除前3个, a = [3,7]
复制列表
a = [9,5,2,3,7]
b = a[:]
最后一个
返回列表中最后一个元素
a = [9,5,2,3,7]
c=a[-1] #7
最后两个
a = [9,5,2,3,7]
a[-2:] #[3,7]
反转列表
a = [9,5,2,3,7]
c=a[::-1] #[7, 3, 2, 5, 9]
修改类型
a = [9,5,2,3,7]
a=list(map(str, a))
print(a) #['9', '5', '2', '3', '7']
频率最高值
a = [1, 1, 1, 2, 3, 3, 3, 3, 4, 4, 4]
print(max(set(a), key = a.count)) #3
合成字符串
a = [9,5,2,3,7]
a=list(map(str, a))
print(','.join(a)) #'9,5,2,3,7'
顺子
import random
import numpy as np
def is_straight(five):
"""
是否是顺子,例如:
[1,2,3,4,5] ==> True
[5,6,7,9] ==> False
[1,3,8] ==> False
"""
no_zero = list(filter(lambda x:x>0, five)) # 剔除0
if len(no_zero) > len(set(no_zero)): # 如有重复
return False # 则不是顺子
no_zero.sort() # 非零元素排序
no_zero = np.array(no_zero) # 转为numpy数组
diff = np.diff(no_zero) # diff为相邻元素的差组成的数组
if np.sum(diff - 1) >len(five)-no_zero.size: # 若diff各元素减1后的和大于0的个数
return False # 则不是顺子
else:
return True
print(is_straight([1,2,3,4,5]))#==> True
print(is_straight([5,6,7,9])) #==> False
print(is_straight([1,3,8])) #==> False
存文件
import numpy as np
a = [9,5,2,3,7]
m=np.array(a)
np.save('./demo.npy',m)
n=np.load('demo.npy')
a=n.tolist()
print(a) #[9,5,2,3,7]
去重复
a = [9,5,5,2,3,7,7]
a =list(set(a))
print(a) #[2, 3, 5, 7, 9]
#方法2
def quchong(list1):
l3 = []
for i in list1:
if i not in l3:
l3.append(i)
return l3
a = [9,5,5,2,3,7,7]
print(quchong(a)) #[9, 5, 2, 3, 7]
#方法3
a = [9,5,2,2,3,7,7]
a=list({}.fromkeys(a).keys())
print(a) #[9, 5, 2, 3, 7]