如何在空格数与 Python 中最后一个元素中的空格数不匹配的地方切断列表
How to chop off list at point where number of spaces does not match number of spaces in last elem in Python
假设我有一个列表
lst = ['hello world', 'los angeles', 'burgers', 'jacky', '12345', '1 1 1 1', '1 2 3 4', '4 3 2 1']
我想从末尾开始数,所以元素“4 3 2 1”,看到它里面有 3 个空格,并保留左边也有 3 个空格的所有内容,直到它到达“12345”,因为它没有 3 个空格。
我将如何实现这样的目标?我不想对其进行硬编码以保持迭代直到达到 0 个空格,因为“12345”可能会更改为“123 45”之类的东西。
最终输出将是:
['1 1 1 1', '1 2 3 4', '4 3 2 1']
您可以反向遍历您的列表,用 3 spaces 捕获值,并在它遇到没有 3 spaces 的东西时中断。输出列表将以相同的相反顺序排列,因此如果您希望它以原始顺序排列,您也需要以相反的顺序打印。
要使其动态化,您可以通过计算初始列表最后一个元素中的 space 来将 space 计数设置为一个变量:
# initial list
lst = ['hello world', 'los angeles', 'burgers', 'jacky', '12345', '1 1 1 1', '1 2 3 4', '4 3 2 1']
# get the space count from the last element
space_count = lst[-1].count(' ')
# make output list to hold values
output_list = []
# iterate in reverse and gather elements with
# correct space count and stop when it hits first
# element without that space count
for x in lst[::-1]:
if x.count(' ') == space_count:
output_list.append(x)
else:
break
print(output_list[::-1])
假设我有一个列表
lst = ['hello world', 'los angeles', 'burgers', 'jacky', '12345', '1 1 1 1', '1 2 3 4', '4 3 2 1']
我想从末尾开始数,所以元素“4 3 2 1”,看到它里面有 3 个空格,并保留左边也有 3 个空格的所有内容,直到它到达“12345”,因为它没有 3 个空格。 我将如何实现这样的目标?我不想对其进行硬编码以保持迭代直到达到 0 个空格,因为“12345”可能会更改为“123 45”之类的东西。 最终输出将是:
['1 1 1 1', '1 2 3 4', '4 3 2 1']
您可以反向遍历您的列表,用 3 spaces 捕获值,并在它遇到没有 3 spaces 的东西时中断。输出列表将以相同的相反顺序排列,因此如果您希望它以原始顺序排列,您也需要以相反的顺序打印。
要使其动态化,您可以通过计算初始列表最后一个元素中的 space 来将 space 计数设置为一个变量:
# initial list
lst = ['hello world', 'los angeles', 'burgers', 'jacky', '12345', '1 1 1 1', '1 2 3 4', '4 3 2 1']
# get the space count from the last element
space_count = lst[-1].count(' ')
# make output list to hold values
output_list = []
# iterate in reverse and gather elements with
# correct space count and stop when it hits first
# element without that space count
for x in lst[::-1]:
if x.count(' ') == space_count:
output_list.append(x)
else:
break
print(output_list[::-1])