嗨,所以我使用python,我正在尝试创建一个函数,让我生成由2个字母组成的单词。我还想数一数字典里到底有多少单词。在
到目前为止,我得到的是:
alphabet = ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o',
'p','q','r','s','t','u','v','w','x','y','z')
count1 = 0
text = " "
def find2LetterWords():
for letter in alphabet:
text += letter
for letter in alphabet:
text +=letter
print text
这是我迄今为止编写的代码,我知道它不对。我只是在做实验。所以如果你能帮我,那就太好了。谢谢。在
来自
itertools
模块的product
正是生成所有可能的2个字母单词的列表所需的内容。在为了比较字典中的哪一个,你需要从其他地方得到
根据评论编辑的答案:
如果你想要一个漂亮的没有功能的一行:
^{pr2}$显然,将
your_dictionary
替换为字典的任何名称。在另一种方法,通过列表理解:
或者自己不打字母表:
^{pr2}$让我们比较一下xvatar,Toote和我的答案:
结果:
换句话说,如果您确实需要一个完整的列表,一定要使用
itertools.product
。但是,生成器速度更快,需要的内存更少,可能就足够了。在相对缓慢itertools.product由于迭代器是意外的,考虑到the documentation表示它与生成器表达式中的嵌套for循环等价。似乎有一些开销。在
相关问题 更多 >
编程相关推荐