![](/img/trans.png)
[英]Is order of elements in list returned by dict.items() same all the time?
[英]How can I list all possible 3 letter combinations from dict.items()?
我正在做一个连续的字母检查器,但我遇到了这个问题,它应该从键盘返回所有三重字母组合,但是,我不明白我上半部做错了什么以及我该怎么做工作? 我只能得到它来打印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解释器的字典都是无序的,因此行的顺序可以不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.