這是我第一次在這里發帖,所以提前對格式問題表示歉意。我正試圖用Python寫一個簡單的程式,該程式需要一個單詞,在本例中是 "ace",并檢查所有可能的單詞,這些單詞可以通過將字母'c'與字母表中的所有字母交換來產生。我試著把我的詞和字母表都變成串列,這樣我就可以創建某種回圈,運行所有的可能性,并最終將它們與可能的英語單詞的字典進行交叉參考(還沒有達到目的)。我沒有很強的編程背景,所以這被證明比我想象的要難,我有限的作業在下面,已經做了幾個小時了,謝謝!
我的代碼......。
我的代碼......(目前還不能作業)
#取字母ace并輸入新的中間字母word = list("ace")
alphabet = list("abcdefghijklmnopqrstuvwxyz"/span>)
wordnew = []
counter = 0
for word[1] in word。
wordnew = word.replace("c", alphabet[0] if counter < 25)
print(wordnew)
uj5u.com熱心網友回復:
注意,你必須在for和in之間放入一個要創建的變數名--word[1]不是一個有效的變數名,所以你的代碼應該以SyntaxError例外失敗。
你可以遍歷字母表中的每一個字母,并創建一個由Ace生成的單詞串列:
alphabet = "abcedfghijklmnopqrstuvwxyz"
詞 = []
for letter in alphabet:
words.append("ace".replace("c", letter)
你甚至可以在一行中做到這一點,使用串列理解:
words = [ "ace"/span>. replace("c", letter) for letter in "abcdefghijklmnopqrstuvwxyz" ]
注意我沒有把 alphabet 變成一個串列--在 Python 中,字串是 iterable,這意味著你可以像使用串列一樣回圈瀏覽它們。
當然,你可以把它們全部列印出來,在最后加上這個:
print(words)
PS:你也可以把"abcdefghijklmnopqrstuvwxyz"變成string.ascii_lowercase,不過你必須匯入string模塊(內置在python中)。
uj5u.com熱心網友回復:
你很接近了,這里有一個簡單的方法
word = "ace" #不需要把它作為一個串列,你希望它是一個字串,所以你可以對它使用.replace。
alphabet = "abcdefghijklmnopqrstuvwxyz" #you can use string in a for loop, in which case they are treated like a list of characters。
for letter in alphabet。
print(word.replace("c",letter) #here you do what you need, here I print it but you can save in a list by doing an .append into one or with a list comprehension which is the prefer mode to make list.
aae
abe
ace
ade
aee
afe
age
ahe
aie
aje
ake
ale
ame
ane
aoe
ape
aqe
are
ase
ate
aue
ave
awe
axe
aye
aze
wordnew = [word.replace("c",letter) forletter inalphabet] #the list comprehension version of the above[/span]。
wordnew
['aae', 'abe', 'ace', 'ade', 'aee', 'afe', 'age', 'ahe', 'aie'。'aje', 'ake', 'alle', 'ame', 'ane', 'aoe', 'ape'。'aqe', 'are', 'ase'。'atte', 'aue', 'ave'。'awe', 'axe', 'aye', 'aze']
uj5u.com熱心網友回復:
word = 'ace'/span>
alphabet = list("abcdefghijklmnopqrstuvwxyz")
對于字母在字母表。
print(word.replace('c'/span>, letter))
uj5u.com熱心網友回復:
如果你想要用字母 "c "替換任何其他字母后的所有可能的 "單詞 "串列,你可以簡單地執行以下操作
word = "ace"/span>
alphabet = "abcdefghijklmnopqrstuvwxyz"
new_words = [word.replace('c', ch) for ch in alphabet]
print(new_words)
uj5u.com熱心網友回復:
word = "ace"/span>
字母 = list("abcdefghijklmnopqrstuvwxyz" )
for letter in alphabet:
wordnew = word.replace("c"/span>, letter)
print(wordnew)
你應該迭代字母表,而不是單詞。
uj5u.com熱心網友回復:
假設你有一個所有存在的單詞的串列,這就可以了:
word = "ace"
字母 = "abcdefghijklmnopqrstuvwxyz"
wordnew = []
counter = 0
# list full of all real words[/span]。
legitWords = ['ace', 'man', 'math', 'marry' 'age'。
'ape', 'are', 'atte', 'awe' 'axe']
for letter in alphabet。 # 回圈瀏覽字母表中的每一個字母。
newWord = word.replace('c', letter) # 將c替換為當前字母。
if newWord in legitWords:
# 添加計數器并追加新詞,如果它真的存在的話。
counter =1
wordnew.append(newWord)
注意,你不必像你所做的那樣將字串轉換成串列,因為它們是可迭代的 .
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/309988.html
標籤:
