繁体   English   中英

使用if else条件列出对Python中字符串的理解

[英]List comprehension for string in Python, using if else condition

hidden_word = ""
for c in word:
     hidden_word += c if c in guesses else'-'
return hidden_word

我正在尝试使用列表推导在一行代码中完成此操作,但是在使if-else条件正常工作时遇到了麻烦,并认为我缺少了一些东西。 基本上,如果word ='yes'并且猜测包含'e',则结果应为'-e-'。 我能够适当地放置字母,但是如果字母没有猜到,则逻辑上很难放入“-”。

我认为您的代码很好-正确无误。 为什么要使用列表推导(然后将其转换回字符串)?

hidden_word = ''.join([c if c in guesses else '-' for c in word])

那真的更好吗? 您可以将其更改为生成器表达式,但是仍然...

hidden_word = ''.join(c if c in guesses else '-' for c in word)

编辑:使用1000个字符的“单词”对此进行测试:

import timeit
setup = """import random
chars = "abcdefghijklmnopqrstuvwxyz"
s = "".join(random.choice(chars) for _ in range(1000))
guesses = "agjoxwz"
"""

t1 = "hidden_word = ''.join([c if c in guesses else '-' for c in s])"
t2 = "hidden_word = ''.join(c if c in guesses else '-' for c in s)"
t3 = """hidden_word = ""
for c in s:
     hidden_word += c if c in guesses else '-'"""

结果:

In [24]: timeit.timeit(setup=setup, stmt=t1)
Out[24]: 100.88796829901968

In [25]: timeit.timeit(setup=setup, stmt=t2)
Out[25]: 147.86355467070305

In [26]: timeit.timeit(setup=setup, stmt=t3)
Out[26]: 247.9441536138757

哇。 因此,列表理解实际上必须更快(并且比生成器表达式更好)。

每个“单词”只有50个字母,差异不那么明显,但是列表理解仍然是成功的:

In [28]: timeit.timeit(setup=setup, stmt=t1)
Out[28]: 5.416419290962722

In [29]: timeit.timeit(setup=setup, stmt=t2)
Out[29]: 7.828715333297168

In [30]: timeit.timeit(setup=setup, stmt=t3)
Out[30]: 7.984714775332918

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM