如何根据特定元素在for循环中获取值
How to get value in for loop based on certain element
我有一个清单。我想从最后完成的句子中获得价值。就像最后一个“。”不是第一,第二或第三。
lst = ["1st", "2nd", "?", "3rd", ".", "4th", "5th", "6th", ".", "7th", "8th"]
我正在努力实现
Output: 1st 2nd? 3rd. 4th 5th 6th.
如何通过 for 循环而不是索引来做到这一点?索引不起作用,因为有无限的列表,每次都是最后一个“。”位置可以不同。
如果我没听错你的问题:
lst = ["1st", "2nd", "?", "3rd", ".", "4th", "5th", "6th", ".", "7th", "8th"]
output = []
start_index = 0
for end_index, char in enumerate(lst):
if char == ".":
output.extend(lst[start_index:end_index + 1])
start_index = end_index + 1
print(" ".join(output))
我有一个清单。我想从最后完成的句子中获得价值。就像最后一个“。”不是第一,第二或第三。
lst = ["1st", "2nd", "?", "3rd", ".", "4th", "5th", "6th", ".", "7th", "8th"]
我正在努力实现
Output: 1st 2nd? 3rd. 4th 5th 6th.
如何通过 for 循环而不是索引来做到这一点?索引不起作用,因为有无限的列表,每次都是最后一个“。”位置可以不同。
如果我没听错你的问题:
lst = ["1st", "2nd", "?", "3rd", ".", "4th", "5th", "6th", ".", "7th", "8th"]
output = []
start_index = 0
for end_index, char in enumerate(lst):
if char == ".":
output.extend(lst[start_index:end_index + 1])
start_index = end_index + 1
print(" ".join(output))