我正在制作一个连续的字母检查器,我遇到了这个问题,它应该从键盘返回所有三个字母组合,但是,我不明白我在最后一部分做错了什么以及如何让它工作?我只能让它打印key()
的 3 个字母组合,而不是字典中的items()
。我正在寻找的结果是"items(("中所有可能的 3 个字母组合都打印在列表中。
keyboard = {'line1':'qwertyuiop',
'line2':'asdfghjkl',
'line3':'zxcvbnm'}
def consequ(key):
a = []
for each_key in key:
for i in range(len(key[each_key])-2):
a.append(each_key[i:i+3])
return a
我通过编写调用函数
consequ(keyboard)
输出由以下代码给出:
['lin', 'ine', 'ne1', 'e1', '1', '', '', 'lin', 'ine', 'ne2', 'e2', '2', '', 'lin', 'ine', 'ne3', 'e3', '3']
所需的输出是:
['QWE', 'Wer', 'Ert', 'RTY', 'Tyu', 'Yui', 'uio', 'iop', 'asd', 'sdf', 'dfg', 'fgh', 'ghj', 'hjk', 'jkl', 'zxc', 'xcv', 'cvb', 'vbn', 'bnm']
如果要
存储所有这些键盘组合,则必须遍历字典的值。但是你写:
a.append(each_key[i:i+3])
# ^ key of the dictionary
所以你必须把它重写为:
def consequ(key):
a = []
for line in key.values():
for i in range(len(line)-2):
a.append(line[i:i+3])
return a
或者更优雅:
def consequ(key):
a = []
for line in key.values():
a += [line[i:i+3] for i in range(len(line)-2)]
return a
这些生成:
>>> consequ(keyboard)
['zxc', 'xcv', 'cvb', 'vbn', 'bnm', 'asd', 'sdf', 'dfg', 'fgh', 'ghj', 'hjk', 'jkl', 'qwe', 'wer', 'ert', 'rty', 'tyu', 'yui', 'uio', 'iop']
请注意,大多数 Python 解释器都有无序字典,因此行的顺序可以不同。