开发者

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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜