我正在尝试运行我的教授给我的一些代码,该代码应该在列表中找到一个项目,并计算出现的次数。当我尝试运行它时,出现错误消息“ SyntaxError:无法分配给文字”。这是代码:
def function(list_of_coins):
count=0
for i in list_of_coins:
if(i == 'Dime'):
count = count+1
return(count)
list_of_coins = ["Penny","Dime","Dime","Nickel","Dime","Penny","Dime"]
print("count: ",function(list_of_coins))
non_dime_list = [1 for 1 in list_of_coins if 1!="Dime"]
print(non_dime_list)
您不能在for循环中使用常量1
,请使用如下所示的变量替换它:
In [913]: non_dime_list = [i for i in list_of_coins if i!="Dime"]
In [914]: print(non_dime_list)
['Penny', 'Nickel', 'Penny']
您在这里有错误[1 for 1 in list_of_coins if 1!="Dime"]
应该为[i for i in list_of_coins if i!="Dime"]