当发现特定的物品时,我试着把清单分开。所以,我可以用数组来处理,如果它是整数列表,没有任何问题,但是我想用链表做同样的事情。下面是我如何使用一个中间的列表(在这里,我以'5‘作为我的具体数字)
num_list =[0,1,2,3,4,5,1,2,3,4,5,2,3,4,5]
arrays = [[num_list[0]]] # array of sub-arrays (starts with first value)
for i in range(1, len(num_list)): # go through each element after the first
if num_list[i] != 5: # If it's larger than the previous
arrays[len(arrays)-1].append(num_list[i]) # Add it to the last sub-array
else: # otherwise
arrays.append([num_list[i]]) # Make a new sub-array
print(arrays)产出:
[[0, 1, 2, 3, 4], [5, 1, 2, 3, 4], [5, 2, 3, 4], [5]]我想用字符串列表来做同样的事情。
发布于 2021-09-23 21:35:44
最简单的选择就是遍历列表,每次点击特殊字符串时“重置”:
my_list = ['apple', 'banana', 'cherry', 'apple', 'pine_apple']
out = []
y = []
for i in my_list:
if y and i == "apple":
out.append(y)
y = []
y.append(i)
out.append(y)
print(out)
# [['apple', 'banana', 'cherry'], ['apple', 'pine_apple']]
# Or with different input:
# my_list = ['a', 'b', 'apple', 'c', 'd', 'apple', 'apple', 'e']
# [['a', 'b'], ['apple', 'c', 'd'], ['apple'], ['apple', 'e']]https://stackoverflow.com/questions/69306945
复制相似问题