टी एल; डॉ
x = [0, [1, 2, 3], [2, 3, [4, 5, [6], []], [7, 8]]]
def find_n(input_list, n):
for el in input_list:
if el == n or (isinstance(el, list) and find_n(el, n)):
return True
return False
print(find_n(x, 6))
ध्यान दें कि, कुछ हद तक दिलचस्प है:
def find_n(input_list, n):
return any([el == n or (isinstance(el, list) and find_n(el, n)) for el in input_list])
return (find_n(x, 6))
50% से अधिक धीमी हैनिष्पादन हेतु।
मूल उत्तर (रों)
क्या आप 2 से अधिक गहराई है तो क्या होगा? यहाँ सामान्य मामले के लिए एक दृष्टिकोण है: हालांकि
x = [0, [1, 2, 3], [2, 3, [4, 5, [6], []], [7, 8]]]
def flatten(input_list):
flat_list = []
for sublist_or_el in input_list:
if isinstance(sublist_or_el, list):
for sublist_or_el2 in flatten(sublist_or_el):
flat_list.append(sublist_or_el2)
else:
flat_list.append(sublist_or_el)
return flat_list
print(6 in flatten(x))
गति के बारे में सुनिश्चित नहीं हैं, लेकिन जैसा कि मैंने कहा, यह एक दृष्टिकोण है कि किसी के लिए उपयोगी हो सकता है है!
संपादित करें - बेहतर (तेज) उत्तर:
यह (यदि n
पाया जाता है, वास्तव में, भले ही यह नहीं पाया जाता है, के बारे में आधे समय वास्तव में ...) जल्दी वापस लौट कर लिया गया समय कम कर देता है। यह @ कर्ट एफ के उत्तर से थोड़ा तेज़ है, और एक ऐसा फ़ंक्शन बनाने से धीमा है जो अधिकतम गहराई (स्वीकार्य उत्तर) मानता है।
x = [0, [1, 2, 3], [2, 3, [4, 5, [6], []], [7, 8]]]
def find_n(input_list, n):
flat_list = []
for sublist_or_el in input_list:
if isinstance(sublist_or_el, list):
if find_n(sublist_or_el, n) == True:
return True
elif sublist_or_el == n:
return True
return False
print(find_n(x, 6))
त्वरित समय (बहुत hacky, माफ करना, आज व्यस्त!):
import time
x = [0, [1, 2, 3], [2, 3, [4, 5, [6], []], [7, 8]]]
def a():
def flatten(input_list):
flat_list = []
for sublist_or_el in input_list:
if isinstance(sublist_or_el, list):
for sublist_or_el2 in flatten(sublist_or_el):
flat_list.append(sublist_or_el2)
else:
flat_list.append(sublist_or_el)
return flat_list
return (6 in flatten(x))
def b():
def find_n(input_list, n):
flat_list = []
for sublist_or_el in input_list:
if isinstance(sublist_or_el, list):
if find_n(sublist_or_el, n) == True:
return True
elif sublist_or_el == n:
return True
return False
return (find_n(x, 6))
zz = 0
for i in range(100000):
start_time = time.clock()
res = a()
zz += time.clock() - start_time
print(a())
print((zz)/100, "seconds")
zz = 0
for i in range(100000):
start_time = time.clock()
res = b()
zz += time.clock() - start_time
print(b())
print((zz)/100, "seconds")
इस मामले में क्या है? – DenCowboy
बस एक परिवर्तनीय नाम है, यह "उप-सूची" –
के लिए खड़ा है आपका समाधान बिल्कुल वही नहीं था जिसकी मुझे आवश्यकता थी, लेकिन यह मेरी समस्या का पता लगाने के लिए पर्याप्त जानकारी दे दी। मैंने अपनी समस्या का समाधान पोस्ट किया। यह नेस्टेड तत्वों को प्रिंट करता है जो किसी अन्य नेस्टेड सूची में नहीं हैं। –