admin管理员组文章数量:1320588
Suppose we have the list:
mylist = [
[
"Hello",
[
"Hi"
]
]
]
How do I check that list containing "Hello"
and "Hi"
exists in mylist
, in specifically this structure without flattening it?
All the solutions are flattening the list, but I need to check for specific structure, like this
Array
|_
—-|_ “Hello”
———|_ “Hi”
——. . .
Suppose we have the list:
mylist = [
[
"Hello",
[
"Hi"
]
]
]
How do I check that list containing "Hello"
and "Hi"
exists in mylist
, in specifically this structure without flattening it?
All the solutions are flattening the list, but I need to check for specific structure, like this
Array
|_
—-|_ “Hello”
———|_ “Hi”
——. . .
Share
Improve this question
edited Jan 17 at 23:12
Barmar
783k56 gold badges547 silver badges660 bronze badges
asked Jan 17 at 23:07
user29249433user29249433
134 bronze badges
5
|
3 Answers
Reset to default 1You can just ask whether it's in there:
["Hello", ["Hi"]] in mylist
Attempt This Online!
To check if the specific nested structure exists in mylist
without flattening it, you can use recursion to traverse the structure and compare it element by element.
def is_structure_present(haystack, needle):
if not isinstance(needle, list) or not isinstance(haystack, list):
return haystack == needle
if len(needle) != len(haystack):
return False
return all(is_structure_present(h, n) for h, n in zip(haystack, needle))
# Your list
mylist = [
[
"Hello",
[
"Hi"
]
]
]
# The structure to check
structure_to_check = [
"Hello",
[
"Hi"
]
]
# Check if the structure exists
print(any(is_structure_present(item, structure_to_check) for item in mylist))
Use the any()
function and the in
operator.
if any("Hello" in sublist and any("Hi" in subsublist for subsublist in sublist if isinstance(subsublist, list)) for sublist in mylist):
print("Hello and Hi were found")
本文标签: How to check for specific structure in nested list pythonStack Overflow
版权声明:本文标题:How to check for specific structure in nested list python - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742087731a2420083.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
Hello
andHi
be at any level of nesting, or do you just need to check at the levels in your example? – Barmar Commented Jan 17 at 23:13mylist[0]
satisfies your criteria? Alternatively, is what you need as a result more likemylist[0][0]
+mylist[0][1][0]
? – JonSG Commented Jan 17 at 23:20