根据当前项目和下一项目的值替换列表中的值

时间:2015-05-12 00:10:23

标签: python for-loop

我正在尝试使用下面的Python代码输出新列表。 print(单词)的输出应为['my','name','is','michael','apples','i','like','cars']

目前,print (words)仅输出['cars']。我在这里缺少什么?

a = 'my name is michael and i like cars'
b = a.split()
words = None
for i, j in enumerate(b):
    words = []
    if j == "and" and b[i+1][0] == "i":
        words.append("apples")
    else:
        words.append(j)
print (words)

5 个答案:

答案 0 :(得分:2)

在循环外创建words,您只看到最后一个单词,因为每次迭代都会将单词设置为空列表:

words = [] # outside the loop
for i, j in enumerate(b):

如果and恰好是最后一个字,您还会得到IndexError。 您可以在枚举中将起始索引设置为1,然后您不需要+1并且将避免任何潜在的错误索引:

words = []
for i, j in enumerate(b, 1):
    if j == "and" and b[i][0] == "i":

你可以把它全部放在列表理解中:

a = 'my name is michael and i like cars'
b = a.split()
words = ["apples" if wrd == "and" and b[i][0] == "i" else wrd for i, wrd in enumerate(b,1)]
print(words)
['my', 'name', 'is', 'michael', 'apples', 'like', 'cars']

您还可以使用iternext来避免编制索引:

a = 'my name is michael and i like cars'
it = iter(a.split())
words = ["apples" if wrd == "and" and next(it," ")[0] == "i" else wrd for wrd in it ]
print(words)
['my', 'name', 'is', 'michael', 'apples', 'like', 'cars']

答案 1 :(得分:1)

你的循环中存在问题。 每次迭代时,都会将words重置为[]

将列表设置为for循环之外的[],如下所示:

words = []
for i, j in enumerate(b):
    if j == "and" and b[i+1][0] == "i":
        words.append("apples")
    else:
        words.append(j)

这应该有用。

答案 2 :(得分:0)

TigerhawkT3是正确的。要修复代码,不要将单词初始化为None,请尝试将其初始化为空数组:

a = 'my name is michael and i like cars'
b = a.split()
words = []
for i, j in enumerate(b):
    if j == "and" and b[i+1][0] == "i":
        words.append("apples")
    else:
        words.append(j)
print (words)

答案 3 :(得分:0)

这应该适合你。

a = 'my name is michael and i like cars'
b = a.split()
words = []
for x in range(len(b)-1):
    if b[x] == "and" and b[x+1] == "i":
        words.append("apples")
    else:
        words.append(j)
print (words)

答案 4 :(得分:0)

我有一个更紧凑的方法。

我认为它更易读且易于理解。您可以参考如下:

这是您的var I delcare回复:

a = 'my name is michael and i like cars'
b = a.split()
words = []
for i, j in enumerate(b):
    if j == "and" and b[i+1][0] == "i":
        words.append("apples")
    else:
        words.append(j)
print (words)