“ SyntaxError:无法分配给文字”,带有for循环的错误

问题描述 投票:0回答:1

我正在尝试运行我的教授给我的一些代码,该代码应该在列表中找到一个项目,并计算出现的次数。当我尝试运行它时,出现错误消息“ 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)
python python-3.x syntax
1个回答
0
投票

您不能在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']

0
投票

您在这里有错误[1 for 1 in list_of_coins if 1!="Dime"]

应该为[i for i in list_of_coins if i!="Dime"]

© www.soinside.com 2019 - 2024. All rights reserved.