繁体   English   中英

为什么代码没有显示错误?

[英]Why does the code not show up with error?

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]

animals.insert(duck_index, "cobra")

duck_index = animals.index("duck")

print animals

既然我还没有在第3行中定义什么duck_index ,为什么代码仍然起作用?

python是一种动态类型的语言。 您不必在声明之前声明或指定类型。

duck_index必须已经被分配-这可能发生在不同的地方。 如果是Web界面,则不知道它们已经定义了什么。 如果其ipython可能已在历史记录中定义。

当您确定列表中有某个值(我们称其为“ duck”)并且您想在该“ duck”值之前将一个新项目插入该列表中而不知道其索引时,请按以下方式处理:

animals.insert(animals.index("duck"), "cobra")

让我知道是否适合您的需求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM