4 回答

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
這將實(shí)現(xiàn)您所描述的內(nèi)容。您可以通過(guò)將選項(xiàng)放入一個(gè)整體列表中而不是使用多個(gè)不同的變量來(lái)使代碼更加整潔,但是您必須明確處理第六個(gè)和第七個(gè)字母相同的事實(shí);不能僅僅因?yàn)槊總€(gè)人都有相同的選擇就保證它們是相同的。
該列表choices_list可以包含每個(gè)原始代碼的子列表,但是當(dāng)您選擇單個(gè)字符時(shí),它在使用時(shí)將與字符串同等工作random.choice,這也使代碼更加整潔。
import random
choices_list = [
'A',
'abcdefghijklmnopqrstuvwxyz',
'aeiouy',
'abcdefghijklmnopqrstuvwxyz',
'aeiouy',
'abcdefghijklmnopqrstuvwxyz',
'eiouy'
]
letters = [random.choice(choices) for choices in choices_list]
word = ''.join(letters[:6] + letters[5:]) # here the 6th letter gets repeated
print(word)
一些示例輸出:
Alaeovve
Aievellu
Ategiwwo
Aeuzykko

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是語(yǔ)法修復(fù):
print(["".join([first, second, third])
for first in firsts
for second in seconds
for third in thirds])
此方法可能會(huì)占用大量?jī)?nèi)存。

TA貢獻(xiàn)1155條經(jīng)驗(yàn) 獲得超0個(gè)贊
有幾件事需要考慮。首先,該str.join()方法接受一個(gè)可迭代對(duì)象(例如 a list),而不是一堆單獨(dú)的元素。正在做
''.join([first, second, third, fourth, fifth])
修復(fù)了這方面的程序。如果您使用的是 Python 3,print()則 是一個(gè)函數(shù),因此您應(yīng)該在整個(gè)列表推導(dǎo)式周圍添加括號(hào)。
擺脫語(yǔ)法障礙,讓我們來(lái)解決一個(gè)更有趣的問(wèn)題:您的程序構(gòu)造每個(gè)(82255680?。┛赡艿膯卧~。這需要很長(zhǎng)的時(shí)間和記憶。您想要的可能只是選擇一個(gè)。當(dāng)然,您可以通過(guò)首先構(gòu)建所有,然后隨機(jī)選擇一個(gè)來(lái)做到這一點(diǎn)。firsts不過(guò),從、seconds等中隨機(jī)挑選一個(gè)字母然后收集這些字母要便宜得多。那么大家一起:
import random
firsts = ['A']
seconds = ['a','b','c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
thirds = ['a', 'e', 'i', 'o', 'u', 'y']
fourths = ['a','b','c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
fifths = ['a', 'e', 'i', 'o', 'u', 'y']
sixths = sevenths = ['a','b','c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
eighths = ['e', 'i', 'o', 'u', 'y']
result = ''.join([
random.choice(firsts),
random.choice(seconds),
random.choice(thirds),
random.choice(fourths),
random.choice(fifths),
random.choice(sixths),
random.choice(sevenths),
random.choice(eighths),
])
print(result)
要從此處改進(jìn)代碼,請(qǐng)嘗試:
找到一種比顯式寫出“數(shù)據(jù)”更簡(jiǎn)潔的方法來(lái)生成“數(shù)據(jù)”。舉個(gè)例子:
import string
seconds = list(string.ascii_lowercase) # you don't even need list()!
不要使用單獨(dú)的變量firsts、seconds等,而是將它們收集到單個(gè)變量中,例如將list每個(gè)原件list作為單個(gè)變量包含的單個(gè)變量str,并包含所有字符。

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超13個(gè)贊
嘗試這個(gè):
import random
sixth=random.choice(sixths)
s='A'+random.choice(seconds)+random.choice(thirds)+random.choice(fourths)+random.choice(fifths)+sixth+sixth+random.choice(eighths)
print(s)
輸出:
Awixonno
Ahiwojjy
etc
添加回答
舉報(bào)