在python列表中的每个字符串的末尾附加字母

时间:2020-04-30 16:50:35

标签: python string list append

我需要通过在列表中每个单词的末尾添加d或ed来使这些单词变时态,具体取决于单词是否以'e'结尾。我正在尝试将它们放在过去时单词的第二个列表中。

我正在尝试使用已经掌握的基本知识。这会在.append行引发错误,表示列表索引必须是整数而不是字符串。我有点卡住,有什么想法吗?

words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
past_tense = []

for i in words:    
    if i[-1] == 'e':
        past_tense.append(words[i] + 'd')
    else:
        past_tense.append(words[i] + 'ed')

7 个答案:

答案 0 :(得分:3)

for i in words: 

这会遍历列表单词中的每个单词。因此,这不是整数,i现在是字符串。因此words[i]将会解决您遇到的错误。

工作代码:

words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
past_tense = []

for index,word in enumerate(words):    
    if word[-1] == 'e':
        past_tense.append(words[index] + 'd')
    else:
        past_tense.append(words[index] + 'ed')

答案 1 :(得分:3)

实际上,for i in words是数组i的一个元素,因此{em}

您不需要数组中的索引,只需要值

words

使用列表理解:

for word in words:    
    if word[-1] == 'e':
        past_tense.append(word + 'd')
    else:
        past_tense.append(word + 'ed')

答案 2 :(得分:3)

您使用iwords[i]视为索引。 i是您执行for i in words:时的单词。将i替换为word会更加清楚。这样您就不会对索引和单词感到困惑。

words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
past_tense = []

for word in words:    
    if word[-1] == 'e':
        past_tense.append(word + 'd')
    else:
        past_tense.append(word + 'ed')

print(past_tense)
# ['adopted', 'baked', 'beamed', 'confided', 'grilled', 'planted', 'timed', 'waved', 'wished']

我们也可以使用列表理解:

past_tense = [word + 'd' if word[-1] == 'e' else word + 'ed' for word in words]

print(past_tense)
# ['adopted', 'baked', 'beamed', 'confided', 'grilled', 'planted', 'timed', 'waved', 'wished']

答案 3 :(得分:2)

使自己适应列表理解:

past_tense = [word + ("d" if word.endswith("e") else "ed")
              for word in words]
print(past_tense)

哪个产量

['adopted', 'baked', 'beamed', 'confided', 'grilled', 'planted', 'timed', 'waved', 'wished']


“旧样式”:

for word in words:
    if word.endswith("e"):
        past_tense.append(word + "d")
    else:
        past_tense.append(word + "ed")

甚至:

for word in words:
    suffix = "d" if word.endswith("e") else "ed"
    past_tense.append(word + suffix)

答案 4 :(得分:1)

这就是您要查找的内容,它只需要进行一些调整(请参阅评论):

model=Sequential()
model.add(SimpleRNN(30,input_dim=nb_features,return_sequences=True))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(p=0.2))

model.add(SimpleRNN(30,return_sequences=False))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.2))

model.add(Dense(20, init='uniform'))
model.add(Activation('relu'))
model.add(Dropout(p=0.2))

model.add(Dense(1, init='uniform'))
model.add(Activation('sigmoid'))

model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
history = model.fit(x_train,y_train,validation_data=(x_test,y_test),batch_size=32,epochs=200)

结果:

words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
past_tense = []

for word in words:
# changed i to word, to reflect what the variable will actually contain.
    if word.endswith('e'):
    # endswith is a nice string method that makes the code very readable.
        past_tense.append(word + 'd')
    else:
        past_tense.append(word + 'ed')

答案 5 :(得分:1)

当您执行for i in words:时,实际上是将'i'设置为单词列表中的实际项(在本例中为单词),因此您可以看到'i'是字符串而不是整数

您的错误来自此行:

past_tense.append(words[i] + 'd')

因为,正如已经说过的那样,您不能使用“ i”作为索引,因为它是一个字符串。

因此您的代码必须是:


words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
past_tense = []

for i in words:    
    if i[-1] == 'e':
        past_tense.append(i + 'd')
    else:
        past_tense.append(i + 'ed')

或者,如果您使用for i in range(0,len(words)):,则意味着“ i”将从0变为单词列表-1的长度:

words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
past_tense = []

for i in range(0,len(words)) :    
    if words[i][-1] == 'e':
        past_tense.append(words[i] + 'd')
    else:
        past_tense.append(words[i] + 'ed')

答案 6 :(得分:1)

这些答案都回答了您的直接问题,但是,如果您要寻找一种更一般的方法来确定动词的过去时形式(例如,“给”为“给”),则更细微的库将是能够以更高的精度处理它。 https://marketplace.visualstudio.com/items?itemName=mgmcdermott.vscode-language-babel是个好人。

python3 -m pip install pattern

然后按照NodeBox的说明,您可以使用其en包对动词进行共轭。

from pattern.en import conjugate
past_tense = []

for word in words:
    past_tense.append(conjugate(word, tense='past'))