python - 如何将元音字母之后的字母附加到列表中?
问题描述
我想创建一个字典,其中的键是字母“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']}
解决方案
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)
- 产生 an
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` 。e_successors
list(a_successors
and likewise for
推荐阅读
- react-hooks - React Konva 中的舞台宽度和高度是否有任何限制?
- node.js - 无法在 mac 终端上安装 npm /react /node js
- javascript - 点击一个简单的按钮时页面刷新?
- javascript - 如何在使用 jquery 的数据表中查看复选框是否已切换并据此执行操作?
- sql - 有没有办法在 ado .net 中使用完全限定的 sql 列名?
- go - KrakenD 插件读取配置设置
- android - Comletable.create 的 RxJava Completable 行为{}
- javascript - 如何提取视频文件大小 HTML5
- javascript - 在 JavaScript 中获取 MS Edge 中的 Microsoft 帐户名称
- javascript - 如何在JS中循环包含对象和对象数组的数组