코드가 괜찮다고 생각합니다. 왜 목록 이해력을 사용하고 (그리고 그것을 다시 문자열로 변환합니까?)
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
이 작동합니다, 당신은 어떤 문제가 있습니까? – salparadise
'hidden_word = ''.join (c는 다른 경우에는 'c'를, 'c'는'word ')'. – ekhumoro