在列表中查找通用子列表 [英] Find generic sub-lists within a list

查看:58
本文介绍了在列表中查找通用子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需学习Python作为我的第一门编码语言即可.给定一个包含许多可能的子列表且元素数量可变的列表,有没有一种方法使用正则表达式(或类似的东西)来标识哪些列表包含子列表,其中1)指定的元素数量和2)给定的内容按特定顺序的类型(包括其他子列表)?例如(用伪代码):

Just learning Python as my first coding language. Given a list with many possible sub-lists which have a variable number of elements, is there a way of using regex (or something similar) to identify which lists contain sub-lists with 1) the number of elements specified and 2) a given type of content in a certain order (including other sub-lists)? For example (in pseudocode):

list1 = [1, 4, 7, ["a", 5, "b"], 2, 4,7,"k",9]
list2 = [1, 4, 7, ["a", "h", "b"], 2]
list3 = [1, 4, 7, ["a", ["a", 6, "b"], "b"], 5, 3]

list4 = [1, 4, 7, ["a", "b"], 3, 4]
list5 = [1, 4, 7, ["a", 5, "b", 7], 3, 4]

if ["a", ., "b"] in listx: # where "." stands for anything, even sub-lists
     print("yes")
else:
     print("no")

list1,list2和list3应该显示为是",而list4和list5应该显示为否".

list1, list2, and list3 should print "yes", but list4 and list5 should print "no".

作为奖励,是否有一种方法可以返回1)找到指定的通用子列表的次数和2)在哪里?例如,让list3返回有2个["a",.,"b"]子列表,分别是list3 [3]和list3 [3] [1]"

As a bonus, is there a way to return 1) the number of times that the specified generic sub-list is found and 2) where? For example, have list3 return "There are 2 ["a", ., "b"] sub-lists, which are list3[3] and list3[3][1]"

我知道我可以将整个内容转换为字符串并进行解析,但这似乎不是一个非常优雅或有效的解决方案.谢谢!

I know I could convert the whole thing to a string and parse it, but this doesn't seem like a very elegant or efficient solution. Thank you!

推荐答案

我同意在这里转换为字符串没有任何意义,但是正则表达式会显式搜索字符串,因此您也不需要这样做.您正在寻找一种可以测试您的规则的递归解决方案,该规则(本质上)

I agree that converting to string doesn't make any sense here, but regular expressions explicitly search strings so you're not looking for that either. You're looking for a recursive solution that tests for your rules, which are (essentially)

somelist是包含一个以字符串"a"开头,以字符串"b"结尾并且包含三个或更多元素的列表.

somelist IS or CONTAINS a list that begins with the string "a", ends with the string "b", and has three or more elements.

将其编码为:

def flat_pass(lst):
    return len(lst) >= 3 and lst[0] == 'a' and lst[-1] == 'b'

现在,您只需要递归即可(以捕获上述规则的内容"部分)

Now you just have to recurse (to catch the "CONTAINS" part of the above rules)

def recurse_pass(lst):
    if len(lst) >= 3 and lst[0] == 'a' and lst[-1] == 'b':
        # base case
        return True
    # otherwise, flow continues...
    for el in lst:
        if isinstance(el, list):
            # recursive case
            if recurse_pass(el):
                return True
    return False

这篇关于在列表中查找通用子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆