python - Find generic sub-lists within a list -
just learning python first coding language. given list many possible sub-lists have variable number of elements, there way of using regex (or similar) identify lists contain sub-lists 1) number of elements specified , 2) given type of content in order (including other sub-lists)? 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: # "." stands anything, sub-lists print("yes") else: print("no")
list1, list2, , list3 should print "yes", list4 , list5 should print "no".
as bonus, there way return 1) number of times specified generic sub-list found , 2) where? example, have list3 return "there 2 ["a", ., "b"] sub-lists, list3[3] , list3[3][1]"
i know convert whole thing string , parse it, doesn't seem elegant or efficient solution. thank you!
i agree converting string doesn't make sense here, regular expressions explicitly search strings you're not looking either. you're looking recursive solution tests rules, (essentially)
somelist or contains list begins string "a", ends string "b", , has 3 or more elements.
codify into:
def flat_pass(lst): return len(lst) >= 3 , lst[0] == 'a' , lst[-1] == 'b'
now have recurse (to catch "contains" part of above rules)
def recurse_pass(lst): if len(lst) >= 3 , lst[0] == 'a' , lst[-1] == 'b': # base case return true # otherwise, flow continues... el in lst: if isinstance(el, list): # recursive case if recurse_pass(el): return true return false
Comments
Post a Comment