什么是命令列表中的Count:Countount:Count + len(Command)]==命令`do in python?

2024-10-05 14:26:47 发布

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

我不知道“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")

Tags: 函数字符串代码命令lenreturnifdef
1条回答
网友
1楼 · 发布于 2024-10-05 14:26:47

您的问题是关闭的,因为Count: Count在您显示的代码中没有任何作用。相反,行为是Count:Count + len(Command)。那最好写成Count: (Count+len(Command))

CommandListCommand都是字符串或列表或类似的数据类型(我将在后面说字符串),而Count是整数。特别地,CountCommandList的索引

表达式CommandList[Count:Count + len(Command)]CommandLista slice。换句话说,该表达式是字符串CommandList的子字符串。子字符串从Count中的索引位置开始,在Count + len(Command)索引位置之前停止。该子字符串的长度与字符串Command的长度相同

所以整条线

if CommandList[Count:Count + len(Command)] == Command:

检查变量Count指向的子字符串是否等于字符串Command。如果子字符串和字符串相等,则执行下一行,即return语句

明白了吗?阅读更多关于Python的片段我给你的链接是一个很好的开始。切片只是Python处理列表和字符串比大多数其他语言好得多的一个原因。这段代码写得有点混乱,所以看起来Count:Count本身就是一个表达式。代码应该使用不同的间距和圆括号来显示内部表达式是Count + len(Command),然后使用冒号。行动顺序又出现了

相关问题 更多 >