在python中比较字符串的最快方法 [英] fastest way to compare strings in python

查看:442
本文介绍了在python中比较字符串的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python编写一个脚本,该脚本将允许用户输入一个字符串,这将是一个指示脚本执行特定操作的命令.为了争辩,我会说我的命令列表是:

I'm writing a script in Python that will allow the user to input a string, which will be a command that instructs the script to perform a specific action. For the sake of argument, I'll say my command list is:

lock
read
write
request
log

现在,我希望用户能够输入单词"log",它将执行特定的操作,这非常简单.但是,我想匹配部分单词.因此,例如,如果用户输入"lo",则它应与"lock"匹配,因为它在列表中较高.我已经尝试过使用ctypes从libc中使用strncmp来完成此操作,但是还没有做到这一点.

Now, I want the user to be able to enter the word "log" and it will peform a specific action, which is very simple. However, I would like to match partial words. So, for example, if a user enters "lo", it should match "lock", as it's higher in the list. I've tried using strncmp from libc using ctypes to accomplish this, but have yet to make heads or tails of it.

推荐答案

如果您接受用户的输入,那么为什么还要担心比较的速度呢?即使是最慢的技术,其速度也将远远超过用户的感知速度.尽可能使用最简单,最易理解的代码,而效率问题则留在紧密的内部循环中.

If you are accepting input from a user, then why are you worried about the speed of comparison? Even the slowest technique will be far faster than the user can perceive. Use the simplest most understandable code you can, and leave efficiency concerns for tight inner loops.

cmds = [
    "lock",
    "read",
    "write",
    "request",
    "log",
    ]

def match_cmd(s):
    matched = [c for c in cmds if c.startswith(s)]
    if matched:
        return matched[0]

这篇关于在python中比较字符串的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆