gpt4 book ai didi

python - 附加带有整数的列表

转载 作者:行者123 更新时间:2023-12-01 02:25:56 25 4
gpt4 key购买 nike

我一直在尝试创建一个小脚本,从模板中获取乱码文本并找到位置。我什至通过反复试验成功地使其发挥作用。问题是......我不知道它是如何工作的。也许有人可以帮我澄清一下?代码如下:

word_list = """something
Location: City
other_something"""
word_list = word_list.split()
indexes = [(index + 1) for index in range(len(word_list)) if word_list[index] == "Location:"]
location = []
location2 = []
for index in indexes:
location2 = location.append(word_list[index])
print location

在意识到城市名称总是出现在短语“Location:”之后之后,我希望 python 找到并打印下一个单词。它甚至有效!现在我不明白的是为什么 location2 保持为空。据我理解,它应该等于位置。或不 ?为什么答案留在 Location 内?请注意,我是一个完全的初学者,所以一个不太简单的答案可能超出我的理解范围。

最佳答案

I hope this makes sense, this code is a bit wacky.

# This line of code assigns a value to the variable word_list
word_list = """something
Location: City
other_something"""
# This line makes a list from the words, with each item in the list being one word
word_list = word_list.split()
# This line loops the variable index over the range of the word_list, and if the index's value is "Location:" it stores
# index+1 into a list called indexes
indexes = [(index + 1) for index in range(len(word_list)) if word_list[index] == "Location:"]
# This makes an empty list called location
location = []
# This makes an empty list called location2
location2 = []
# This loops over the indexes in indexes
for index in indexes:
# This line of code never stores anything to location2, because location.append appends to the list called
# 'location', and since location.append does not return a value to store, location2 remains empty
location2 = location.append(word_list[index])
# This line prints the list called location.
print location

关于python - 附加带有整数的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47403176/

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