Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> Python

Python: नेस्टेड सूची से जटिल डेटा प्रकार (list, tuple, dict, set) वाली पंक्तियाँ निकालना

Python में नेस्टेड सूची से उन पंक्तियों को निकालना जिनमें कम से कम एक जटिल डेटा प्रकार (list, tuple, dict, set) मौजूद हो। isinstance() फ़ंक्शन का उपयोग किया जाता है।

उदाहरण

my_list = [
    [13, 1, 35],                    # केवल int
    [23, [44, 54], 85],             # list शामिल
    [66],                           # केवल int
    [75, (81, 2), 29, 7]            # tuple शामिल
]

print("मूल सूची:")
for i, row in enumerate(my_list):
    types = [type(e).__name__ for e in row]
    print(f"  पंक्ति {i}: {row} → प्रकार: {types}")

# विधि 1: isinstance + any + list comprehension (मूल लेख)
my_result = [
    row for row in my_list 
    if any(isinstance(element, (list, tuple, dict, set)) for element in row)
]

print("\nजटिल डेटा प्रकार वाली पंक्तियाँ:")
for row in my_result:
    print(f"  {row}")

आउटपुट

मूल सूची:
  पंक्ति 0: [13, 1, 35] → प्रकार: ['int', 'int', 'int']
  पंक्ति 1: [23, [44, 54], 85] → प्रकार: ['int', 'list', 'int']
  पंक्ति 2: [66] → प्रकार: ['int']
  पंक्ति 3: [75, (81, 2), 29, 7] → प्रकार: ['int', 'tuple', 'int', 'int']

जटिल डेटा प्रकार वाली पंक्तियाँ:
  [23, [44, 54], 85]
  [75, (81, 2), 29, 7]

विस्तृत विश्लेषण

# प्रत्येक पंक्ति के लिए विस्तृत जानकारी
complex_types = (list, tuple, dict, set)

for i, row in enumerate(my_list):
    complex_elements = [
        (elem, type(elem).__name__) 
        for elem in row 
        if isinstance(elem, complex_types)
    ]
    if complex_elements:
        print(f"पंक्ति {i}: {complex_elements}")
    else:
        print(f"पंक्ति {i}: कोई जटिल प्रकार नहीं")

आउटपुट

पंक्ति 0: कोई जटिल प्रकार नहीं
पंक्ति 1: [([44, 54], 'list')]
पंक्ति 2: कोई जटिल प्रकार नहीं
पंक्ति 3: [((81, 2), 'tuple')]

फंक्शन के रूप में

def extract_rows_with_complex_types(matrix, types=(list, tuple, dict, set)):
    """निर्दिष्ट जटिल प्रकार वाली पंक्तियाँ निकालें"""
    return [
        row for row in matrix 
        if any(isinstance(elem, types) for elem in row)
    ]

def extract_rows_with_type_info(matrix, types=(list, tuple, dict, set)):
    """पंक्ति और मिले जटिल तत्वों की जानकारी के साथ"""
    result = []
    for row in matrix:
        found = [(elem, type(elem).__name__) for elem in row if isinstance(elem, types)]
        if found:
            result.append({'row': row, 'complex_elements': found})
    return result

# उपयोग
print("\nसिंपल:", extract_rows_with_complex_types(my_list))
print("\nविस्तृत:", extract_rows_with_type_info(my_list))

आउटपुट

सिंपल: [[23, [44, 54], 85], [75, (81, 2), 29, 7]]

विस्तृत: [
  {'row': [23, [44, 54], 85], 'complex_elements': [([44, 54], 'list')]},
  {'row': [75, (81, 2), 29, 7], 'complex_elements': [((81, 2), 'tuple')]}
]

विविधताएं

1. विशिष्ट प्रकार के लिए फ़िल्टर

# केवल list वाली पंक्तियाँ
only_list = [row for row in my_list if any(isinstance(e, list) for e in row)]

# केवल tuple वाली पंक्तियाँ
only_tuple = [row for row in my_list if any(isinstance(e, tuple) for e in row)]

# list या dict (tuple, set नहीं)
list_or_dict = [row for row in my_list if any(isinstance(e, (list, dict)) for e in row)]

2. नेस्टेड गहराई जांचना (रिकर्सिव)

def has_complex_nested(obj, types=(list, tuple, dict, set), max_depth=3, current_depth=0):
    """रिकर्सिवली जांचें कि ऑब्जेक्ट में नेस्टेड जटिल प्रकार है"""
    if current_depth >= max_depth:
        return False
    if isinstance(obj, types):
        return True
    if isinstance(obj, (list, tuple, set)):
        return any(has_complex_nested(item, types, max_depth, current_depth+1) for item in obj)
    if isinstance(obj, dict):
        return any(has_complex_nested(v, types, max_depth, current_depth+1) for v in obj.values())
    return False

# टेस्ट
deep_list = [[1, 2], [3, [4, [5, 6]]], [7, 8]]
for row in deep_list:
    print(f"{row}: {has_complex_nested(row)}")

3. Pandas में मिश्रित प्रकार के कॉलम

import pandas as pd

# ऑब्जेक्ट dtype कॉलम में मिश्रित प्रकार
s = pd.Series([
    [1, 2, 3],
    [4, [5, 6]],
    "string",
    {"a": 1},
    (7, 8)
])

# जटिल प्रकार वाली पंक्तियाँ
mask = s.apply(lambda x: any(isinstance(e, (list, tuple, dict, set)) for e in (x if isinstance(x, (list, tuple, set)) else [x])))
print("जटिल प्रकार वाली प्रविष्टियाँ:\n", s[mask])

प्रकार जांच के लिए isinstance() पैटर्न

जांचकोड
कोई भी कंटेनरisinstance(x, (list, tuple, set, dict))
सीक्वेंस (list, tuple)isinstance(x, (list, tuple))
मैपिंग (dict)isinstance(x, dict)
इटरेबल (स्ट्रिंग नहीं)hasattr(x, '__iter__') and not isinstance(x, str)
संख्यात्मकisinstance(x, (int, float, complex))
  1. - पायथन में टुपल एलिमेंट के डेटा टाइप्स प्राप्त करें

    जब टुपल एलिमेंट के डेटा टाइप्स प्राप्त करने की आवश्यकता होती है, तो map मेथड और type मेथड का उपयोग किया जा सकता है।map फ़ंक्शन एक दिए गए फ़ंक्शन/ऑपरेशन को इटरेबल (जैसे सूची, टुपल) में प्रत्येक आइटम पर लागू करता है। यह परिणाम के रूप में एक सूची लौटाता है।type मेथड उस आर्ग्युमेंट के क्लास टाइप को लौटा

  1. - पायथन में सूची का योग (स्ट्रिंग प्रकार के साथ)

    इस ट्यूटोरियल में, हम एक प्रोग्राम लिखेंगे जो सूची से सभी संख्याओं को जोड़ता है। सूची में संख्याएं स्ट्रिंग या पूर्णांक प्रारूप में हो सकती हैं। उदाहरण देखें।इनपुटrandom_list = [1, 10, tutorialspoint, 2020, tutorialspoint@2020, 2020]आउटपुट4051प्रोग्राम लिखने के लिए नीचे दिए गए चरणों का पालन करें।सूच

  1. - पायथन में स्टैंडर्ड डेटा टाइप्स

    मेमोरी में स्टोर किया गया डेटा कई प्रकार का हो सकता है। उदाहरण के लिए, किसी व्यक्ति की उम्र न्यूमेरिक मान के रूप में स्टोर की जाती है और उसका पता अल्फान्यूमेरिक कैरेक्टर्स के रूप में स्टोर किया जाता है। पायथन में विभिन्न स्टैंडर्ड डेटा टाइप्स हैं जिनका उपयोग उन पर संभव ऑपरेशन्स और प्रत्येक के लिए स