我一直在尝试创建一个小脚本,从模板中获取乱码文本并找到位置。我甚至设法通过反复试验使其成功。问题是.....我不知道它是如何工作的。也许有人可以为我澄清一下? 这是代码:
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
在意识到城市的名字总是出现在短语"位置:"我想让python找到并打印下一个单词。它甚至有效!现在,我不知道的部分是为什么location2保持空白。据我所知,它应该等于位置。或不 ?为什么答案与位置保持一致? 请注意,我是一个完整的初学者,所以一个不会很简单的答案可能超出了我的理解范围。
答案 0 :(得分:1)
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
答案 1 :(得分:1)
您可以利用列表的.index()
属性
word_list = """something
Location: City
other_something""".split()
print word_list[word_list.index('Location:')+1]
在这种情况下,这只会打印'City'
。 index()
返回第一个参数指定的元素的索引。通过在'Location'
索引中添加一个,您可以访问word_list
的下一个元素,如果word_string
的格式没有改变,它将始终是位置。