我对python的经验很少,我相信即使我的标题也是不正确的措辞。我有一个程序,当你键入一个键列表并按Enter键时,它会播放一个音符。但是要使它工作,你需要在每个键之间按空格键。我想让它接受说eflkjh而不是e f l k j h。我该怎么做?
soundBinary = input(" > ")
for note in soundBinary.split():
if note == "q": #rest
freq = 37
elif note == "w": #b
freq = 280
elif note == "e": #b
freq = 300
elif note == "r": #b
freq = 320
elif note == "t": #b
freq = 340
elif note == "y": #b
freq = 360
elif note == "u": #b
freq = 380
elif note == "i": #b
freq = 400
elif note == "o": #b
freq = 440
elif note == "p": #b
freq = 460
elif note == "a": #b
freq = 480
elif note == "s": #b
freq = 500
elif note == "d": #b
freq = 520
elif note == "f": #b
freq = 540
elif note == "g": #b
freq = 560
elif note == "h": #b
freq = 580
elif note == "j": #high c
freq = 600
elif note == "k": #low c
freq = 620
elif note == "l": #d
freq = 640
elif note == "z": #e
freq = 660
elif note == "x": #f
freq = 680
elif note == "c": #g
freq = 700
elif note == "v": #a
freq = 720
elif note == "b": #b
freq = 740
elif note == "n": #b
freq = 760
elif note == "m": #b
freq = 780
winsound.Beep(freq, rate)
答案 0 :(得分:2)
尝试以下方法:
for note in soundBinary:
if note == "q":
....
示例:
string = "abcdefg"
for char in string:
print char
输出:
scottsmudger@ns207588:~ $ python test.py
a
b
c
d
e
f
g
答案 1 :(得分:1)
两部分:
(1)只需遍历输入字符串的字符:
for note in soundBinary:
这样可以按顺序为您提供字符,而无需拆分任何内容。
(2)构建一个参考字典并将其用作查找列表:
note_id : {
'q':37, 'w':280, 'e':300, 'r':320, 't':340, 'y': 360,
'u':380 # et cetera
}
现在,您的程序在上面的循环中使用它:
for note in soundBinary:
winsound.Beep( note_id[note] )
这会让你感动吗?将该引用列表放在程序的顶部使得实际的逻辑流程更容易阅读。