Python中的随机函数
如何使用随机函数(在Python中)从txt列表中选择一个字符串?Python中的随机函数
我想随机从列表:
import random
import sys
filename = sys.argv[1]
f = open(filename)
f.close()
print random.choice(f)
是这段代码好吗?
> import random
> list_of_strings = open(sys.argv[1]).readlines()
> randomly_chosen_string = random.choice(list_of_strings)
> help(random.choice)
Help on method choice in module random:
choice(self, seq) method of random.Random instance
Choose a random element from a non-empty sequence.
import random
file = open("file.txt", "r")
list = file.readlines()
def getline():
return list[random.randint(0,(len(list) - 1))]
getline()
假设file.txt的包含sonething像 AAA BBB CCC 等等 (每行一个字) 然后,将工作 – krzysz00 2010-05-22 11:42:04
+1为了简洁,欢迎SO!但是请不要使用'list'作为变量名,因为'list()'是Python中的一个函数名。另外,您应该查看'with'语句来读取文件。 :] – 2010-05-22 12:34:54
对不起,不了解太多的Python,这是第一个进入我的脑海和顺便说一句,我认为普通的lisp不会扼杀有变量和名为list的函数,那么为什么Python – krzysz00 2010-05-22 14:01:33
选择听起来是正确的。 – Stephen 2010-05-22 02:29:39
至少在提问前假装看看非常非常好的文档...... – 2010-05-22 02:31:24
您可以编辑标题或扩展您的问题。正如所写,没有提到随机函数本身的任何具体问题。 – bernie 2010-05-22 02:41:47