首页 > 解决方案 > 如何将元音字母之后的字母附加到列表中?

问题描述

我想创建一个字典,其中的键是字母“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']}

标签: pythonlistdictionary

解决方案


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)
  • 产生 anIndentationError: 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 = {}or vowel_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_successorslist(a_successorsand likewise for


推荐阅读