首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >‘Count:Count’in‘`CommandList[Count:Count + len(Command)] ==命令在python中做什么?

‘Count:Count’in‘`CommandList[Count:Count + len(Command)] ==命令在python中做什么?
EN

Stack Overflow用户
提问于 2019-01-01 23:10:39
回答 1查看 44关注 0票数 0

我不知道“计数”在我的代码中做了什么。下面是第4行中使用的函数

我试着打印它,但它给了我一个错误。CommandList既是一个字符串变量,也是一个命令。

代码语言:javascript
运行
复制
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")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-01 23:19:42

您的问题取消了,因为Count: Count在您显示的代码中什么也不做。更确切地说,行为是Count:Count + len(Command)。最好写成Count: (Count+len(Command))

CommandListCommand都是字符串或列表或类似的数据类型(下面我会说字符串),而Count是一个整数。特别是,CountCommandList的索引。

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

所以整条线

代码语言:javascript
运行
复制
if CommandList[Count:Count + len(Command)] == Command:

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53999656

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档