burim:python:python-labs:loesung_prf2_sorted_list_exception_kommentiert.py
"""
Loesung zur Uebungsaufgabe bzgl. des Sortierens von gemischten Listen.
"""
NUMBERS = [13, 9, 5, 14]  # Liste bestehend aus Integers
WORDS = ["mad", "dp", "bh", "bc"]  # Liste bestehend aus Sting-Elementen
MIXED_LIST = [1, "c", 3, 2, "a", 8, "b", 4]  # gemischte Liste

NUMBERS.sort()
WORDS.sort()
# MIXED_LIST.sort()  # dies war in Python 2 noch moeglich

print(NUMBERS)
print(WORDS)
print(MIXED_LIST)

try:  # versuche die gemischte Liste zu sortieren
    MIXED_LIST_SORTED = sorted(MIXED_LIST)
except TypeError:  # und fange den 'TypeError' ab
    # Ziehe alle Integers aus der gemischten Liste
    LISTINTS = sorted([x for x in MIXED_LIST if type(x) is int])
    # listStrs = [x for x in MIXED_LIST if type(x) is str]
    # Ziehe alle Strings aus der gemischten Liste
    LISTSTRS = sorted([x for x in MIXED_LIST if isinstance(x, str)])
    # Fuege die Liste wieder zusammen:
    MIXED_LIST_SORTED = LISTINTS + LISTSTRS

print(MIXED_LIST_SORTED)  # Ausgabe der gemischten Liste
burim/python/python-labs/loesung_prf2_sorted_list_exception_kommentiert.py.txt · Last modified: 2019/01/21 20:55 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki