这是我的代码和一些注释:
import re
import itertools
nouns = ['bacon', 'cheese', 'eggs', 'milk', 'houses', 'dog']
CC = ['and', 'or']
def search_and_replace(text):
noun_patt = r'\b(' + '|'.join(nouns) + r')\b'
CC_patt = r'\b(' + '|'.join(CC) + r')\b'
patt = r'({0},? )+{1} {0}'.format(noun_patt, CC_patt)
searched = re.search(patt, text)
phrase = searched.group()
print "Check re.search match object exists:", phrase # "bacon, eggs, and milk" prints
perm_phrase = itertools.permutations(phrase)
print "Check permutated list exists:", perm_phrase # permutation object position in memory prints
perm_phrase_list = list(perm_phrase)
print "Permutated object as list:", perm_phrase_list # THIS IS WHERE MEMORY MAXES AND COMPUTER FREEZES!!!
# So print does not happen.
return perm_phrase_list
def main():
text = "I like bacon, eggs, and milk"
print search_and_replace(text)
if __name__ == '__main__':
main()
从我在代码中的注释可以看出,这行代码perm_phrase_list = list(perm_phrase)
占用了太多的物理内存,以至于我的电脑死机了。(我在每行代码之后打印以找出问题开始的位置,我通常不会在函数中打印)。我想知道为什么在尝试从排列创建此列表时会发生这种情况?
如果我可以在这段代码中使用 permutations 方法将非常方便!否则,我只需要创建等效的东西来重新排序列表中的元素。
我正在使用 Python 2.7