如何解决python中的“namererror”,而数字是可解的,而单词是不可解的?

2024-05-15 11:16:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个新写名单的名字,但当我想删除某个名字是重复了几次名单,它给了我一个错误的名字。 我试过了。。。在。但这适用于数字,而不是坚果的名字。 我不知道为什么???你知道吗

这个有效。。。你知道吗

 x = [1, 2, 3, 4, 2, 2, 3]
 while 2 in x: x.remove(2)
 print(x)
 [1, 3, 4, 3]

但是你看。。。你知道吗

 new = [ Behrad, Mohammad, Behrad, Behrad, Leyla, Bahman]
 while Behrad in new: new.remove(Behrad)
 print(new)

而后面的代码带有名称,它给了我以下错误:

 NameError                                 Traceback (most recent call 
  last)
  <ipython-input-55-c57503438675> in <module>
   ----> 1 new = [ Behrad, Mohammad, Behrad, Behrad, Leyla, Bahman]
  2 while Behrad in new: new.remove(Behrad)
  3 print(new)

  NameError: name 'Behrad' is not defined

我以为贝拉德这个名字会从名单上删除。 谢谢你的帮助


Tags: innew错误数字名字remove坚果print
2条回答

我上网后得到的答案是:

def Remove(duplicate):
  final_list = []
  for num in duplicate:
    if num not in final_list:
       final_list.append(num)
  return final_list

duplicate = ["mohammad", "leyla", "behrad", "behrad", "behrad"] 
print(Remove(duplicate))

你可以简单地复制和粘贴我的代码在你的jupyter笔记本和看到真正的结果。。。你知道吗

享受。。!你知道吗

你的代码错了。您需要使用“(引号)来定义变量是字符串。如果不加引号,Python就知道给定的名称是变量,需要返回它们的值。你知道吗

这是正确的代码:

 new = [ "Behrad", "Mohammad", "Behrad", "Behrad", "Leyla", "Bahman"]
 while "Behrad" in new:
     new.remove("Behrad")
 print(new)

相关问题 更多 >