我想創建一個字典,其中鍵是字母“a”和“e”。如果 'a' 或 'e' 之后的字符是一個字母,那么我想將它附加到一個不應重復的串列中。
text= 'there is a sea apple'
a = []
e = []
for i in range(len(text)):
if text[i 1].isalpha() and i == 'a':
vowel_dict['a'] = []
vowel_dict['a'].append(text[i])
if text[i 1].isalpha() and i == 'e':
vowel_dict['e'] = []
vowel_dict['e'].append(text[i])
print('vowel_dict)
我希望我的輸出是:
{'a': ['p'], 'e': ['r', 'a']}
uj5u.com熱心網友回復:
text= 'there is a sea apple'
a = []
e = []
for i in range(len(text)):
if text[i 1].isalpha() and i == 'a':
vowel_dict['a'] = []
vowel_dict['a'].append(text[i])
if text[i 1].isalpha() and i == 'e':
vowel_dict['e'] = []
vowel_dict['e'].append(text[i])
print('vowel_dict)
- 產生一個
IndentationError: unexpected indent因為你的第二行和后續行比前一行無緣無故地更深一個縮進級別。 - 另外:
print('vowel_dict)產生一個SyntaxError: EOL while scanning string literal因為print(vowel_dict)。 - 接下來你有一個
IndexError: string index out of range因為在 for 回圈的最后一次迭代中,i == len(text) - 1并且i 1 == len(text)是一個太大的整數,無法索引到text。要解決這個問題,for i in range(len(text)):應該是for i in range(len(text) - 1):. - 在那之后你有,
NameError: name 'vowel_dict' is not defined因為你從來沒有宣告vowel_dict。您必須在使用之前宣告一個變數。您可以通過在 for 回圈之前執行vowel_dict = {}orvowel_dict = dict()(它們等效)來實作。
text= 'there is a sea apple'
a = []
e = []
vowel_dict = {}
for i in range(len(text) - 1):
if text[i 1].isalpha() and i == 'a':
vowel_dict['a'] = []
vowel_dict['a'].append(text[i])
if text[i 1].isalpha() and i == 'e':
vowel_dict['e'] = []
vowel_dict['e'].append(text[i])
print(vowel_dict)
現在您應該能夠運行您的代碼,但它仍然沒有做正確的事情。玩弄它。
下次,請嘗試運行您的代碼并修復阻止其運行的任何錯誤。網上有很多地方可以運行您的代碼:例如 repl.it、pythontutor.com、thonny.org(最后兩個特別適合初學者)。
這是一種方法:
s = 'there is a sea apple'
N = len(s)
a_successors = set()
e_successors = set()
for i in range(N-1):
curr = s[i]
after = s[i 1]
if after.isalpha():
if curr == 'a':
a_successors.add(next_)
elif curr == 'e':
e_successors.add(next_)
vowel_dict = {'a': a_successors, 'e': e_successors}
print(vowel_dict)
印刷:
{'a': {'p'}, 'e': {'r', 'a'}}
如果你想要a_successors并e_successors作為串列,只需執行list(a_successors) and likewise fore_successors`。
uj5u.com熱心網友回復:
下面的內容比您的解決方案更有趣,因為它使用defaultdict,enumerate和set. 它可能也有點“Python 式”。
from collections import defaultdict
text= 'there is a sea apple'
vowels = defaultdict(set)
for i, char in enumerate(text[:-1]):
if text[i 1].isalpha() and char in 'ae':
vowels[char].add(text[i 1])
print(vowels)
uj5u.com熱心網友回復:
您可以使用正則運算式來簡化代碼,盡管它可能效率較低:
import re
text = 'there is a sea apple'
d = {k: set(re.findall(rf"{k}(\w)", text)) for k in 'ae'}
print(d) # {'a': {'p'}, 'e': {'r', 'a'}}
uj5u.com熱心網友回復:
您可以使用以 'a' 和 'e' 為鍵并以集合為值的字典。為了獲得每個字符及其后繼字符,您可以在文本上使用 zip。然后檢查該字符是否在字典中并且其后繼是一個字母。將下一個字母添加到集合中將確保每個后繼字母只會被計算一次:
text= 'there is a sea apple'
result = {'a':set(), 'e':set()} # set of successor letters for 'a' and 'e'
for v,n in zip(text,text[1:]):
if v in result and n.isalpha(): # a/e followed by a letter ?
result[v].add(n) # add to key's set
print(result)
{'a': {'p'}, 'e': {'a', 'r'}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/348926.html
