我需要从文本文件中打印两个不同的随机行.下面是打印一行的代码,如何打印两行不同而不是两行相同的可能性.
import random
with open('Long films') as f:
lines = f.readlines()
print(random.choice(lines))
最佳答案 您正在寻找
random.sample
:
Return a
k
length list of unique elements chosen from the population
sequence. Used for random sampling without replacement.
import random
with open('Long films') as f:
lines = f.readlines()
print(random.sample(lines, 2))
如果您要查找非唯一行,请改用random.choices.