首页 > 解决方案 > `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")

标签: python

解决方案


您的问题已关闭,因为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),然后使用冒号。操作顺序再次显现!


推荐阅读