+-

如果file.txt包含:
appple
cheese
cake
tree
pie
使用这个:
nameFile = ("/path/to/file.txt")
nameLines = open(nameFile).read().splitlines()
randomName = random.choice(nameLines)
这只会从file.txt中打印1行
我如何打印1-2行(随机)?
例:
第一个输出=苹果
第二输出= cheesetree
第三输出=饼状
第四输出=蛋糕
最佳答案
要生成多个随机数,请使用
random.sample().您可以随机化样本大小:
randomNames = random.sample(nameLines, random.randint(1, 2))
这将为您提供一个包含1或2个项目的列表,从输入中选择一个随机样本.
演示:
>>> import random
>>> nameLines = '''\
... apple
... cheese
... cake
... tree
... pie
... '''.splitlines()
>>> random.sample(nameLines, random.randint(1, 2))
['apple', 'cake']
>>> random.sample(nameLines, random.randint(1, 2))
['cheese']
如果需要,使用str.join()将单词连接在一起:
>>> ' '.join(random.sample(nameLines, random.randint(1, 2)))
'pie cake'
>>> ' '.join(random.sample(nameLines, random.randint(1, 2)))
'cake'
点击查看更多相关文章
转载注明原文:Python – 从文件中打印随机行数 - 乐贴网