本文介绍了如何将字符串处理成子列表层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是示例表单,稍后我将尝试用语言对其进行解释.我有一个分解字符串的清单...

[a, a, a, b, a, a, b, a, c, a, b, a, a, c, a, c, a]

其中b是标准1,c是标准2

我想将其分成这样的列表:

[a, a, a, [b, a, a, [b, a, c], a, [b, a, a, c], a, c], a]

因此,我想对字符串进行处理,以便在我通过该字符串时,如果该项目符合条件1,则打开一个新列表,如果该项目符合条件2,则关闭列表并返回上一级.

我试图做这样的事情,但是效果不是很好.

def sublist(self, l):
  for line in list:
    if not b:
    self.data.append(line)
  else:
    sublist(l[line:])       #<-----  not sure how to recurse it.

在堆栈溢出之前,我已经看到将列表分成大小相等的列表,但是没有人使用一组条件将其分成子列表.

我对python还是很陌生,所以我对数据结构和迭代器工具不太熟悉.

解决方案

您要去的地方:

lst = "aaabaabacabaacaca"

def go(it):
    for x in it:
        if x == 'b':
            yield [x] + list(go(it))
        else:
            yield x
            if x == 'c':
                break 


print list(go(iter(lst)))

This is the example form, I'll try to explain it in words later.I have a list from breaking up a string...

say

[a, a, a, b, a, a, b, a, c, a, b, a, a, c, a, c, a]

where b is criteria 1 and c is criteria 2

I want to break it into a list like this:

[a, a, a, [b, a, a, [b, a, c], a, [b, a, a, c], a, c], a]

So I want to process the string such that when I go through it, if the item matches criteria 1, open a new list, if item matches criteria 2, close the list and return one level above.

I've tried to do something like this, but it's not working very well.

def sublist(self, l):
  for line in list:
    if not b:
    self.data.append(line)
  else:
    sublist(l[line:])       #<-----  not sure how to recurse it.

I've seen breaking list into equal sized list before on stackoverflow, but not one breaking into sublist using a set of criteria.

I'm fairly new to python, so I'm not too familiar with the data structures and iterator tools.

解决方案

here you go:

lst = "aaabaabacabaacaca"

def go(it):
    for x in it:
        if x == 'b':
            yield [x] + list(go(it))
        else:
            yield x
            if x == 'c':
                break 


print list(go(iter(lst)))

这篇关于如何将字符串处理成子列表层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 19:01