python - `CommandList[Count:Count + len(Command)] == Command`中的`Count : Count`在python中做了什么?
问题描述
我不知道 'Count : Count' 在我的代码中做了什么。下面是第 4 行使用的函数
我尝试打印它,但它给了我一个错误。CommandList 是一个字符串变量以及 Command。
def GetPositionOfCommand(CommandList, Command):
Position = Count = 0
while Count <= len(CommandList) - len(Command):
if CommandList[Count:Count + len(Command)] == Command:
return Position
elif CommandList[Count] == ",":
Position += 1
Count += 1
return Position
Position = GetPositionOfCommand(Items[IndexOfItem].Commands, "get")
解决方案
您的问题已关闭,因为Count: Count
您显示的代码中没有任何内容。相反,行动是Count:Count + len(Command)
。最好写成Count: (Count+len(Command))
.
CommandList
和都是Command
字符串或列表或类似的数据类型(我将在下文中说字符串),Count
而是整数。特别Count
是 是 的索引CommandList
。
表达式CommandList[Count:Count + len(Command)]
是的切片。CommandList
换句话说,该表达式是 string 的子字符串CommandList
。该子字符串从索引位置开始并在索引位置Count
之前停止Count + len(Command)
。该子字符串的长度与字符串的长度相同Command
。
因此整条线
if CommandList[Count:Count + len(Command)] == Command:
检查变量指向的子字符串Count
是否等于字符串Command
。如果子字符串和字符串相等,则执行下一行,即return
语句。
明白了吗?阅读更多关于 Python 的切片——我给你的链接是一个好的开始。切片只是 Python 处理列表和字符串比大多数其他语言更好的原因之一。代码写得有点混乱,所以它Count:Count
本身看起来像是一个表达式。代码应该使用不同的间距,也许还有括号来显示内部表达式是Count + len(Command)
,然后使用冒号。操作顺序再次显现!
推荐阅读
- javascript - 在three.js中使用不同材料的多个立方体
- rust - 如何在 actix-web 中将不可变对象注入到服务代码中?
- ruby - Pry 使用过时的 Ruby 版本运行
- reactjs - 滑块状态的 React Redux 设置
- arrays - typescript 不检查 Array.map 结果的类型吗?
- xcode - Xcode 引用了错误的 Mono 路径
- java - 使用流将 Map 结构中的 Map 展平
- amazon-web-services - 如何获取元数据并附加到现有的 html 文件
- angular - 位于子目录中的迁移模块
- javascript - 如何从另一个函数内部的firebase函数内部访问一个函数