我有一个小程序,从一个文本文件打印随机行。我想把已经选择的行保存在一个列表或其他东西中,这样下次就不会重复了。在
示例
text_database.txt
- This is a line
- This is an other line
- This is a test line
- That sucks
这是一个例子,说明输出是随机的,并且程序重复行–它是而不是终端中的直接输出:
This is a line
That sucks
That sucks
That sucks
This is a line
我的代码:
^{pr2}$我尝试了:
with open (text_database) as f:
lines_list = []
lines = f.readlines()
random_tmp = random.choice(lines)
if random_tmp not in lines_list:
lines_list.append(random_tmp)
print(random_tmp)
它不起作用,我需要帮助。谢谢你们。在
我使用
^{pr2}$.read().splitlines()
而不是.readlines()
来清除每行的尾随空格(换行符)。我也可以这样做:以下是文档中对
random.sample
的描述:或者,您可以对行列表进行无序处理,然后对它们进行迭代。在
编辑-我想我现在明白了。怎么样?在
这是一个非常混乱的解决方案,但我已经测试过了
这段代码的意思是遍历f中的所有行并将它们放入一个列表中。然后它选择0和列表长度之间的一个随机数,并打印与该数字对应的随机行
希望这有帮助!欢迎使用堆栈溢出
相关问题 更多 >
编程相关推荐