如何用 python 列表中的 int 替换字符串?

How to replace string with an int in list in python?

在下面的列表中,我想用 0 替换“Sun”,用 1 替换“Rain”。我该怎么做?

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

您可以使用列表推导来做到这一点:

precipitation = [0 if x == 'Sun' else 1 for x in precipitation]

试试这个...

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)

@Gabip 的答案的详细说明,使用布尔值在数字上表示为 0 和 1 的事实:

[int(x=='Sun') for x in precipitation]

使用 map()

添加到已经存在的答案中
list(map(lambda x: 0 if x=='Sun' else 1,a))

您可以试试这个来避免循环和列表理解