我不知道“计数”在我的代码中做了什么。下面是第4行中使用的函数
我试着打印它,但它给了我一个错误。CommandList既是一个字符串变量,也是一个命令。
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")
发布于 2019-01-01 23:19:42
您的问题取消了,因为Count: Count
在您显示的代码中什么也不做。更确切地说,行为是Count:Count + len(Command)
。最好写成Count: (Count+len(Command))
。
CommandList
和Command
都是字符串或列表或类似的数据类型(下面我会说字符串),而Count
是一个整数。特别是,Count
是CommandList
的索引。
表达式CommandList[Count:Count + len(Command)]
是a slice of CommandList
。换句话说,该表达式是字符串CommandList
的子字符串。该子字符串从Count
中保持的索引位置开始,并在索引位置Count + len(Command)
之前停止。该子字符串的长度与字符串Command
的长度相同。
所以整条线
if CommandList[Count:Count + len(Command)] == Command:
检查变量Count
指向的子字符串是否等于字符串Command
。如果子字符串与字符串相等,则执行下一行,即return
语句。
清楚了吗?阅读更多关于Python切片的内容--我给您的链接是一个很好的开始。切片只是Python处理列表和字符串比大多数其他语言好得多的原因之一。代码编写得有点混乱,所以看起来Count:Count
本身就是一个表达式。代码应该使用不同的间距和括号,以显示内部表达式是Count + len(Command)
,之后使用冒号。行动的秩序再次显现出来!
https://stackoverflow.com/questions/53999656
复制相似问题