我希望能夠通過其坐標/位置在字典中找到某個位置。如果讓我們說鍵是 x,并且每個字符代表一個 y 值,我希望能夠通過詢問我正在尋找的地方的輸入來找到字典中某個地方的某個字符是什么。
前任
1: 'Hi'
2: 'My name is Stan'
3: 'What is your name?'
如果你想把這些地方:
(1,0) = 'H' # the H in 'Hey'
(4,1) = Out of bounds # since key 4 do not exist
(1,2) = Out of bounds #since there is nothing after 'Hi'
(2,2) = Space #in between 'My' and 'name'
(3,3) = t # the t in 'What'
我試圖混合一些if回圈,但沒有任何好的結果。我假設我可以使用一些函式len()來查找分配給每個鍵的字符長度,但無法完全執行此操作。
有這樣的東西作為開始,但它需要更多。
for key, value in indexed_file.items():
if key != row:
print('Out of bounds')
關于如何繼續執行此操作的任何提示都非常有價值。注意:我不想使用任何匯入。
uj5u.com熱心網友回復:
您可以切片字典/串列并使用try/except來捕獲IndexError(和KeyError):
d = {1: 'Hi',
2: 'My name is Stan',
3: 'What is your name?' }
def get_letter(key, pos):
try:
print(d[key][pos])
except IndexError:
print('Out of bounds!')
except KeyError:
print('No Key!')
例子:
>>> get_letter(1,0)
H
>>> get_letter(2,15)
Out of bounds!
如果你想有兩個相同的結果IndexError和KeyError:
def get_letter(key, pos):
try:
print(d[key][pos])
except (IndexError, KeyError):
print('Out of bounds!')
uj5u.com熱心網友回復:
您可以使用字典上的 get 方法和字串上的下標來獲取字符,如果沒有可訪問的字符,則回傳越界字串:
def getLetter(d,k,i):
return d.get(k,"")[i:i 1] or 'Out of Bounds'
uj5u.com熱心網友回復:
我會做的很簡單;
d= {1:"Hi",2:"My name is stan", 3:"What is your name?"}
input_cords = (1,1)
sent = input_cords[0] #Get sentence
if d.get(sent):
try:
res = d[sent][input_cords]
except IndexError:
print("out of bounds")
else:
print("No key")
uj5u.com熱心網友回復:
為了沒有錯誤處理的樂趣
dct = {1: 'Hi', 2: 'My name is Stan', 3: 'What is your name?'}
x, y = 3, 0
l = s[y:y 1] if (s := dct.get(x, '')) else ''
print(l if l else 'Out of bounds')
W
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/366896.html
上一篇:用全名更改縮寫的州名
