在下面的列表中,我想將“Sun”替換為 0,將“Rain”替換為 1。我該怎么做?precipitation = ["Sun", "Rain", "Rain", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Rain", "Rain", "Rain", "Rain"]for i in precipitation: if precipitation[i] == "Sun": precipitation[i] = 0 else: precipitation[i] = 1
4 回答

慕田峪7331174
TA貢獻1828條經(jīng)驗 獲得超13個贊
您可以使用列表理解來做到這一點:
precipitation = [0 if x == 'Sun' else 1 for x in precipitation]

慕后森
TA貢獻1802條經(jīng)驗 獲得超5個贊
使用布爾值用數(shù)字表示為 0 和 1 的事實來詳細闡述 @Gabip 的答案:
[int(x=='Sun') for x in precipitation]

拉莫斯之舞
TA貢獻1820條經(jīng)驗 獲得超10個贊
添加到已經(jīng)存在的答案中,使用map()
list(map(lambda x: 0 if x=='Sun' else 1,a))
您可以嘗試這樣做以避免循環(huán)和列表理解

慕尼黑8549860
TA貢獻1818條經(jīng)驗 獲得超11個贊
嘗試這個...
precipitation = ["Sun", "Rain", "Rain", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Sun", "Rain", "Rain", "Rain", "Rain"]
for i in range(len(precipitation)):
if precipitation[i] == "Sun":
precipitation[i] = 0
else:
precipitation[i] = 1
print(precipitation)
添加回答
舉報
0/150
提交
取消