Python中的随机函数

时间:2010-05-22 02:28:00

标签: python function random

如何使用随机函数(在Python中)从txt列表中选择一个字符串?


我想从列表中随机出发:

import random
import sys
filename = sys.argv[1]
f = open(filename)
f.close()
print  random.choice(f)

这段代码好吗?

2 个答案:

答案 0 :(得分:3)

> 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.

答案 1 :(得分:1)

import random

file = open("file.txt", "r")
list = file.readlines()
def getline ():
    return list[random.randint(0,(len(list) - 1))]

getline()