![](/img/trans.png)
[英]How to get the remaining sample after using random.sample() in Python?
[英]Printing random lines in .txt file using random.sample() Python 3
我有一個文本文件,每行有 15 個引號。 我的目標是在控制台上打印不是一個而是兩個隨機引號。 我的代碼有效,但它的格式有問題。
我想逐行打印引號,使其清晰易讀。 但是我以列表格式打印的代碼.. 例如,帶有方括號'[]' 引號'' 和'\n'。
代碼:
import random
def primary():
f = open("quotes.txt")
quotes = f.readlines()
f.close()
sampling = random.sample(quotes, 2)
print(sampling)
if __name__== "__main__":
primary()
結果:
['Truth is stranger than fiction\n', 'Anything added dilutes everything else\n']
我確信將 function 定義為根據索引號以某種方式打印會解決但不確定如何解決。
嘗試這個:)
import random
def primary():
f = open("quotes.txt")
quotes = f.readlines()
f.close()
sampling = random.sample(quotes, 2)
for sample in sampling: print(sample)
if __name__== "__main__":
primary()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.