【问题标题】:python app gets stuck on shuffle and looppython应用程序卡在随机播放和循环中
【发布时间】:2010-10-01 23:40:54
【问题描述】:

我正在用 python 处理这个小块,当我运行它时,它永远不会超过 print 'c' 行并且卡在 while 循环中。我究竟做错了什么?链接到文本文件: http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip

enter code here
import sys
import random

inp = open('5desk.txt', 'r')
lis = inp.readlines()
inp.close()
print lis

def proc():

 a = raw_input('What are the scrambled letters? ')
 copy = list(a)
 print a
 print copy
 if a in lis:
  print a, ' is a word'
 elif a not in lis:
  print 'c'
  while copy not in lis:
   random.shuffle(copy)
  print 'd'


 print "A word that ", a, " might equal is:\n", copy


if __name__ == "__main__":
 proc()

【问题讨论】:

  • 1 个空格的缩进很糟糕。另外,copy 是一个变量名,因为它是标准库中的一个模块。
  • 如下所述,不能保证您一定会随机进入比赛。你可能想要的是 itertools.permutations()。

标签: python list loops


【解决方案1】:

readline() 和 readlines() 保留输入的每一行的尾随换行符; raw_input() 去除换行符。因此永远不会匹配。

当从外部源读取输入时,使用 strip() 函数清理内容通常是个好主意 - 默认情况下,它会从输入的每一端删除空格。

试试:

lis = [line.strip() for line in inp.readlines()]

【讨论】:

  • 我试过这个并且识别部分工作,它仍然有洗牌的问题。我将如何将 itertools.permutations() 应用于此?我之前尝试过,但无法做到。
  • itertools.permutations 可能比较棘手的一点是,如果你给它一个字符串,它会返回单个字符的元组,然后你需要用 "".join() 将它们融合回字符串或类似的。
【解决方案2】:

也许你的意思是这样的:

while copy in lis:

无论哪种方式,都不能保证重新排列字母最终会创建一个在列表中或不在列表中的单词。特别是如果输入只包含一个字母,那么随机播放将完全没有效果。以随机顺序遍历所有排列可能会更好,如果到达列表末尾并出现错误则退出循环。

【讨论】:

  • 好吧,每次我尝试它时,我都会使用列表中的一个词。 not in lis 的原因是因为它会随机播放,直到碰到列表中的一个单词。
猜你喜欢
  • 2016-12-29
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多