首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中条件下找到eqal项时拆分字符串列表

在python中条件下找到eqal项时拆分字符串列表
EN

Stack Overflow用户
提问于 2021-09-23 21:12:21
回答 1查看 31关注 0票数 0

当发现特定的物品时,我试着把清单分开。所以,我可以用数组来处理,如果它是整数列表,没有任何问题,但是我想用链表做同样的事情。下面是我如何使用一个中间的列表(在这里,我以'5‘作为我的具体数字)

代码语言:javascript
复制
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)

产出:

代码语言:javascript
复制
[[0, 1, 2, 3, 4], [5, 1, 2, 3, 4], [5, 2, 3, 4], [5]]

我想用字符串列表来做同样的事情。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-23 21:35:44

最简单的选择就是遍历列表,每次点击特殊字符串时“重置”:

代码语言:javascript
复制
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']]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69306945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档