哪一种是更快的条件字符串格式还是传统的if/else格式?

2024-04-24 23:35:46 发布

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

Method 1 - Conventional if/else:

from collections import Counter

sentence = Counter(input("What would you like to say? ").lower())
sentence_length = 0

for k, v in sentence.items():
    if v > 1:
        print("There are {} {}'s in this sentence.".format(v, k))
    else:
        print("There is {} {} in this sentence.".format(v, k))
    sentence_length += v

print("There are {} words, including spaces, in total.".format(sentence_length))
^{2}$
from collections import Counter

sentence = Counter(input("What would you like to say? ").lower())
sentence_length = 0

for k, v in sentence.items():
    print("There {} {} {}{} in this sentence.".format(("are" if v > 1 else "is"), v, k, ("'s" if v > 1 else "")))
    sentence_length += v

print("There are {} words, including spaces, in total.".format(sentence_length))

这两个代码段都用于计算特定字符在句子中出现的次数。这两种方法的区别在于“for”语句内部的部分-条件字符串格式或常规if/else。我在想哪种方法更有效。你知道吗


Tags: infromimportformatforifcounterthis
1条回答
网友
1楼 · 发布于 2024-04-24 23:35:46

由于两者在算法上没有区别,所以回答这个问题的唯一方法就是测试它。他说

当然,很难对包含input的程序进行基准测试,因此首先我计算了键入所需句子所花的时间,然后用常量赋值和time.sleep(7.8)替换了它。他说

两个版本都用了不到8秒的时间。7.8秒以外的大部分时间都花在print。他说

但是,根据{},版本1比版本2快了约0.0005秒,加速率约为0.006%。他说

(顺便说一句,你得到的加速比从str.format%要快得多。)

我敢肯定,几乎所有的差异都归结为str.format有更多的参数,而不是if语句和if表达式之间的差异。他说

当然,细节可能取决于您选择的Python实现,也可能取决于您的版本和平台,取决于您输入的字符串,最重要的是,您输入的速度有多快。所以,如果这0.006%的差异对某些东西来说很重要,你真的需要自己测试一下。他说

相关问题 更多 >