如何使用For循环替换列表中的元素

时间:2019-07-06 01:18:40

标签: python list

如何为列表verbs中的每个动词添加“ ing”?如果要在每个单词后加上“ ing”(例如“皮划艇,哭泣...”)到新列表中,那很容易,但我不知道如何用“皮划艇,哭泣,走路”来覆盖原始动词列表。 ..“

我不相信追加是正确的方法,因为这只是将每个单词对象添加到动词列表的末尾。谢谢大家。

verbs = ["kayak", "cry", "walk", "eat", "drink", "fly"]

for words in verbs:
    words = words + "ing"

4 个答案:

答案 0 :(得分:8)

您可以使用列表理解:

verbs = ["kayak", "cry", "walk", "eat", "drink", "fly"]
verbs = [words + "ing" for words in verbs]

答案 1 :(得分:3)

如果您特别需要使用for循环,最简单的方法是使用列表的索引,如下所示:

for i in range(len(verbs)):
    verbs[i] += 'ing'

答案 2 :(得分:0)

var objectCollection = [];
var o = {}

o.foo = 1;
objectCollection.push(o);

o.foo = 2;
objectCollection.push(o);


console.log(objectCollection)    //All 2 elemets are the same object

objectCollection[0].foo = 100;
console.log(objectCollection);

答案 3 :(得分:0)

verbs = ["kayak", "cry", "walk", "eat", "drink", "fly"]
ing=[]
for i in range(len(verbs)):
    ing.append(verbs[i]+"ing")

print(ing)