Random function in Python
How can I use the random function (in Python) to choose a string from a txt list?
开发者_运维问答i want random from a list :
import random
import sys
filename = sys.argv[1]
f = open(filename)
f.close()
print random.choice(f)
is this code ok ?
> 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()
精彩评论