问题:将列表中的4替换为7
kk = [1,2,3,4,4,3]
方法一:for循环
for i in range(len(kk)):
if kk[i] == 4:
kk[i] =7
else: pass
print(kk)
输出:
[1, 2, 3, 7, 7, 3]
方法二: numpy
import numpy as np
# list 转 np
aaa = np.array(kk)
aaa[np.where(aaa==4)]=7
# np 转 list
kk = aaa.tolist()
print(kk)
输出:
[1, 2, 3, 7, 7, 3]
方法三:pandas
import pandas as pd
# list 转 pd
df = pd.DataFrame(kk, columns=['col1'])
change={4:7}
new_df = df.replace({'col1': change})
# pd 转 list
kk = new_df['col1'].values.tolist()
print(kk)
输出:
[1, 2, 3, 7, 7, 3]