我不知道“Count:Count”在我的代码中起什么作用。下面是第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")
您的问题是关闭的,因为
Count: Count
在您显示的代码中没有任何作用。相反,行为是Count:Count + len(Command)
。那最好写成Count: (Count+len(Command))
CommandList
和Command
都是字符串或列表或类似的数据类型(我将在后面说字符串),而Count
是整数。特别地,Count
是CommandList
的索引表达式
CommandList[Count:Count + len(Command)]
是CommandList
的a slice。换句话说,该表达式是字符串CommandList
的子字符串。子字符串从Count
中的索引位置开始,在Count + len(Command)
索引位置之前停止。该子字符串的长度与字符串Command
的长度相同所以整条线
检查变量
Count
指向的子字符串是否等于字符串Command
。如果子字符串和字符串相等,则执行下一行,即return
语句明白了吗?阅读更多关于Python的片段我给你的链接是一个很好的开始。切片只是Python处理列表和字符串比大多数其他语言好得多的一个原因。这段代码写得有点混乱,所以看起来
Count:Count
本身就是一个表达式。代码应该使用不同的间距和圆括号来显示内部表达式是Count + len(Command)
,然后使用冒号。行动顺序又出现了相关问题 更多 >
编程相关推荐