我正在嘗試創建一個函式,該函式接受一個字串作為輸入,并為每個相應的字母回傳北約字母表。我已經嘗試這樣做了好幾天了,我感到非常沮喪,我不知道如何將它們視為陣列或字串,我想象的方法是使兩個字母元素/字串相等,例如Nato=alphabet 并使用 for i 回圈僅列印出輸入字母。關于如何/做什么的任何提示或想法?
import numpy as np
def textToNato(plaintext):
plaintext=plaintext.lower()
plaintext="-".join(plaintext)
plaintext=plaintext.split()
Nato=np.array(["Alpha","Bravo","Charlie","Delta","Echo","Foxtrot",
"Golf","Kilo","Lima","Mike","November","Oscar",
"Papa","Quebec","Romeo","Sierra","Tango","Uniform"
"Victor","Whiskey","Xray","Yankee","Zulu"])
alphabet=np.array(["a","b","c","d","e","f","g","k","l","m","n","o"
,"p","q","r","s","t","u","v","w","x","y","z"])
new=plaintext
for i in range(len(Nato)): # i have no idea what i'am trying to do here
new=np.append(alphabet[i],Nato[i])
return new
uj5u.com熱心網友回復:
我會創建一個不同的資料結構來進行查找。您可以制作一個字典,了解字母表中的每個字母所指的單詞。然后遍歷單詞中的每個字母,在字典中查找該字母,并將北約字母添加到串列中。
nato_alphabet = {
'a': 'Alpha', 'b': 'Bravo', 'c': 'Charlie', 'd': 'Delta', 'e': 'Echo',
'f': 'Foxtrot', 'g': 'Golf', 'h': 'Hotel', 'i': 'India', 'j': 'Juliet',
'k': 'Kilo', 'l': 'Lima', 'm': 'Mike', 'n': 'November', 'o': 'Oscar',
'p': 'Papa', 'q': 'Quebec', 'r': 'Romeo', 's': 'Sierra', 't': 'Tango',
'u': 'Uniform', 'v': 'Victor', 'w': 'Whiskey', 'x': 'Xray', 'y': 'Yankee',
'z': 'Zulu'
}
def word_to_nato(word):
output = []
for letter in word:
output.append(nato_alphabet[letter.lower()])
return output
print(word_to_nato("foobar"))
['Foxtrot', 'Oscar', 'Oscar', 'Bravo', 'Alpha', 'Romeo']
uj5u.com熱心網友回復:
我發現您的代碼有兩個問題:
# ...
plaintext = plaintext.split()
# ...
# "plaintext"'s value here is overwritten by
# each element of alphabet
for plaintext in alphabet:
# ...
# Below compares each element of the alphabet
# with the alphabet list.
# You want to check each element of plaintext against
# each element of alphabet, to find the index and get the
# corresponding element of Nato
if plaintext == alphabet:
# ...
我想你想做的是:
- 遍歷輸入的每個元素,以及
- 遍歷字母表中的每個字母以找到索引,然后
- 使用該索引來獲取相應的拼音字母詞。
可以這樣做:
output = ''
for char1 in plaintext:
found = False
for i, char2 in enumerate(alphabet):
if char1 == char2:
output = Nato[i] ', '
found = True
break
if not found: output = 'not found'
return output
一種更簡單有效的方法是使用字典(又名哈希圖):
nato_map = {
'a' : 'Alpha',
'b' : 'Bravo',
# ...
}
output = ''
for char in plaintext:
output = nato_map[char] ', '
這樣,查找是在恒定時間內進行的,而不需要遍歷 Nato 串列的每個元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/333186.html
上一篇:函式first_name和last_namecoursera
下一篇:決議python中的布爾運算式
