我正在撰寫代碼,它從 3 個單獨的檔案中獲取前綴、根詞和后綴,并將它們放在一起(這是我的代碼中的“finalword”變數)。該代碼有效并生成一個單詞。
我想要做的是,生成很多單詞(比如說 1000 個),而不必一遍又一遍地運行我的代碼。我考慮過使用while回圈:
while finalword != 1:
print(finalword)
但這所做的只是列印相同的最終詞,而不是每次都列印一個新詞。如何讓這個回圈每次都列印新的唯一單詞?
這是我的代碼:
import random
# finalword components
file = open("prefixes.py", "r") # opening word list
prefixes = file.read().split("\n") # splitting all the lines
xprefixes = random.choice(prefixes) # getting a random word from the file
file = open("words.py", "r")
words = file.read().split("\n")
xwords = random.choice(words)
file = open("suffix.py", "r")
suffix = file.read().split("\n")
xsuffix = random.choice(suffix)
# final word, which combines words from the lists
finalword = (f'{xprefixes}{xwords}{xsuffix}')
print(finalword)
uj5u.com熱心網友回復:
你將不得不做出某種重復的隨機選擇。是否回圈執行取決于您。
因為我沒有你的檔案,所以我做這個是為了提供一個最小的可重復的例子。
prefixes = ['un', 'non', 're']
words = ['read', 'yield', 'sing']
suffixes = ['ing', 'able']
現在解決你的問題,沒有回圈我會使用random.choices:
import random
N = 6
# finalword components
xprefixes = random.choices(prefixes, k = N) # getting a random word from the file
xwords = random.choices(words, k = N)
xsuffixes = random.choices(suffixes, k = N)
# final word, which combines words from the lists
finalwords = [f'{xprefix}{xword}{xsuffix}' for xprefix, xword, xsuffix in zip(xprefixes, xwords, xsuffixes)]
for finalword in finalwords:
print(finalword)
或者,如果您想減少記憶體,只需將您的random.choice和連接呼叫放在一個回圈中:
for _ in range(N):
xprefixes = random.choice(prefixes) # getting a random word from the file
xwords = random.choice(words)
xsuffix = random.choice(suffixes)
# final word, which combines words from the lists
finalword = f'{xprefixes}{xwords}{xsuffix}'
print(finalword)
unreadable
reyielding
rereadable
resinging
rereading
unreadable
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/436061.html
上一篇:如何在請求用戶輸入的for回圈中使用try-except命令?
下一篇:java三個最低分
