gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:11:24 25 4
gpt4 key购买 nike

我正在尝试使用下面的Python代码来输出一个新列表。 print (words) 的输出应该是 ['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)

最佳答案

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

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']

关于python - 根据当前项目和下一项的值替换列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30179642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com