簡體   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