1. Reguläre Ausdrücke (Befehlszusammenfassung)
  2. Import von Modulen
  3. Import von Paketen
  4. Tipps und Tricks
  5. Offizielle Dokumentation
  6. Interne Dokumentation
  7. Spezielle Module
  8. Pandas
  9. CSV-Listen einlesen

Import von Modulen

Der Befehl import dient zum Einbinden von Modulen, die in der Regel auch vom Anwender installiert werden müssen, was (wie mehrfach gezeigt) am besten mit pip3 erfolgt. Lediglich die Standardmodule, wie math, sind mit jeder Python-Installation vorhanden, aber nicht standardmäßig geladen! Eine versionsabhängige Liste gibt es hier (3.6). Sollte es Probleme geben, so ist jeweils zu kontrollieren, ob die aktuell verwendete Pythonversion das Modul unterstützt.

Jedes Modul kann nur einmal geladen werden, sodass ein wiederholtes Laden ignoriert wird. Wenn Sie tatsächlich möchten, dass es erneut geladen/analysiert wird, müssen es mit reload() geladen werden. Allerdings können einzelne Funktionen durch mehrfaches from ... import ... (as) importiert werden.

Ein from math import * lädt alles aus dem Modul math in den lokalen Bereich, beispielsweise pi. Wenn man jetzt pi einen neuen Wert zuweist, wird dieser der aktuelle Wert.

from math import *
from math import pi as PI
print(pi,PI)
pi = 2*pi
print(pi,PI)

Ein einfaches import math erlaubt einen Zugriff auf Funktionen/Variablen nur über den Modulnamen:

import math
print(math.pi)
pi = 2*math.pi
print(pi,math.pi)

Ein eigenes Modul

Fibinaccizahlen sind eine Zahlenreihe, die mit den beiden Werten 1 1 starten und jeweils die Summe als neue Zahl hinzufügen: 1 1 2 3 5 ... Der folgende Pythoncode sei als Datei fibo.py im lokalen Verzeichnis /usr/local/lib/python/ gespeichert.

# Hinweis
# fibo.py, lokal gespeichert in /usr/local/lib/python

def fib(n):    # print Fibonaccireihe bis n
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

def fib2(n):   # return Fibonaccireihe bis n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

Diese Datei kann jetzt als Modul eingebunden werden, wobei die Funktionen nicht direkt, sonder nur über den Modulnamen zugänglich sind;

import sys
sys.path.append('/usr/local/lib/python/')#  enthält Datei fibo.py

import fibo
fibo.fib(1000)
print()
print(fibo.fib2(100))

fib = fibo.fib
fib(500)

print(fibo.__name__)

Es lassen sich auch einzelne Funktionen eines Moduls einbinden:

import sys
sys.path.append('/usr/local/lib/python/')#  enthält Datei fibo.py

from fibo import fib
fib(500)
print(fib.__name__)

Die Änderung der Namen ist ebenfalls möglich:

import sys
sys.path.append('/usr/local/lib/python/')#  enthält Datei fibo.py

import fibo as fib
fib.fib(500)

from fibo import fib as fibonacci
fibonacci(500)

print(fib.__name__,fibonacci.__name__)

Übersicht über die vorhandenen Funktionen:

import sys
sys.path.append('/usr/local/lib/python/')#  enthält Datei fibo.py

import fibo
print(dir(fibo))
print()

a = [1, 2, 3, 4, 5]
fib = fibo.fib
print(dir())

Ein weiteres und einfaches Beisiel finden Sie hier: https://cito.github.io/byte_of_python/read/making-modules.html

Werden die Module ohne Pfadangabe importiert, wird die Variable sys.path ausgewertet, die alle definierten Modulpfade enthält:

import pkgutil
import sys
print(sys.path,"\n")  # Ausgabe der definierten Suchpfade für Python Module/Pakete

search_path = None    # oder ['.'] , falls ein spezielles Verzeichnis untersucht werden soll
all_modules = [x[1] for x in pkgutil.iter_modules(path=search_path)]
print(all_modules)

Standardmodule

Einige sind direkt Teil des Python-Interpreters, andere werden geladen, sind aber bei jeder Python-Installation vorhanden. Ein Installieren ist daher ncht nötig!

import sys
print(dir(sys))#   

Alle fest eingebunden FUnktionen/Variablen erhält man mit

print(dir(__builtins__))

Eine Zusammenstellung der Standardmodule gibt es hier: https://docs.python.org/3/library/functions.html#sorted

Import von Paketen

# Hinweis
from meinPaket.meinModul import meins

bedeutet:

  • meinPaket: Ein Verzeichnis im PYthon-Suchpfad einschließlich einer Datei __init__.py
  • meinModul: Eine Datei meinModul.py in dem Verzeichnis
  • meins: Eine Klasse aus meinModul.py
  • Da dieses Thema nicht weiter in diesem Kurs behandelt wird, wird auf The Definitive Guide to Python import Statements verwiesen.

    Tipps und Tricks

    1. In-Place Swapping Of Two Numbers

    x, y = 10, 20
    print(x, y) 
    x, y = y, x 
    print(x, y) 

    2. Reversing a string in Python

    a = "GeeksForGeeks"
    print("Reverse is", a[::-1]) 

    3. Create a single string from all the elements in list

    a = ["Geeks", "For", "Geeks"] 
    print(" ".join(a)) 

    4. Chaining Of Comparison Operators.

    n = 10
    result = 1 < n < 20
    print(result) 
    result = 1 > n <= 9
    print(result) 

    5. Print The File Path Of Imported Modules.

    import os 
    import socket 
    
    print(os) 
    print(socket) 

    6. Use Of Enums In Python.

    class MyName: 
    	Geeks, For, Geeks = range(3) 
    
    print(MyName.Geeks) 
    print(MyName.For) 
    print(MyName.Geeks) 

    7. Return Multiple Values From Functions.

    def x(): 
    	return 1, 2, 3, 4
    a, b, c, d = x() 
    
    print(a, b, c, d) 

    8. Find The Most Frequent Value In A List.

    test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] 
    print(max(set(test), key = test.count)) 

    9. Check The Memory Usage Of An Object.

    import sys 
    x = 1
    print(sys.getsizeof(x)) 

    10. Print string N times.

    n = 2
    a = "GeeksforGeeks"
    print(a * n) 

    11. Checking if two words are anagrams

    from collections import Counter 
    def is_anagram(str1, str2): 
    	return Counter(str1) == Counter(str2) 
    
    # or without having to import anything 
    def is_anagram(str1, str2): 
    	return sorted(str1) == sorted(str2) 
    
    print(is_anagram('geek', 'eegk')) 
    print(is_anagram('geek', 'peek'))

    11. Flatten Lists

    import itertools
    a = [[1, 2], [3, 4], [5, 6]]
    b = list(itertools.chain.from_iterable(a))
    print(b)

    12. Combining two lists

    a=[‘a’,’b’,’c’,’d’]
    b=[‘e’,’f’,’g’,’h’]for x, y in zip(a, b):
     print(x,y)

    13. Negative Indexing Lists

    a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
    print(a[-3:-1]) 

    14. Transposing a matrix

    mat = [[1, 2, 3], [4, 5, 6]]
    new_mat=zip(*mat)
    for row in new_mat:
     print(row)

    15. Chaining comparison operators

    a = 5
    b = 10
    c = 3
    print(c < a)
    print(a < b)
    print(c < a < b)

    16. Inverting Dictionary

    dict1={‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
    dict2={v: k for k, v in dict1.items()}
    print(dict2)

    17. Iterating over dictionary key and value pairs

    dict1={‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
    for a, b in dict1.iteritems():
    print (‘{: {}’.format(a,b))

    18 Merging Dictionaries

    x = {'a': 1, 'b': 2}
    y = {'b': 3, 'c': 4}
    z = {**x, **y}
    print(z)

    19. Initializing empty containers

    a_list = list()
    a_dict = dict()
    a_map = map()
    a_set = set()

    20. Initializing List filled with some numbers

    #listA contains 1000 0's
    listA=[0]*1000 
    #listB contains 1000 2's
    listB=[2]*1000

    21. Chained Assignment

    If you need multiple variables to reference the same object, you can use the chained assignment:

    x = y = z = 2
    print(x, y, z)

    22. Chained Comparison

    You can merge multiple comparisons to a single Python expression by chaining the comparison operators. This expression returns True if all comparisons are correct or False otherwise:

    x = 5
    print(2 < x <= 8)
    print(6 < x <= 8)

    This is similar to (2 < x) and (x <= 8) and (6 < x) and (x ≤ 8), but more compact and requires x to be evaluated only once.

    This is also legal:

    print(2 < x > 4)

    You can chain more than two comparisons:

    x = 2
    y = 8
    print(0 < x < 4 < y < 16)

    Ordinary multiple assignments are not all Python can do. You don’t need the same number of elements on the left and right sides:

    x, *y, z = 2, 4, 8, 16
    print(x)
    print(y)
    print(z)

    In this case, x takes the first value (2) because it comes first. z is the last and takes the last value (8). y takes all other values packed in a list because it has the asterisk (*y).

    23. Merge Dictionaries

    One way to merge two or more dictionaries is by unpacking them in a new dict:

    x = {'u': 1}
    y = {'v': 2}
    z = {**x, **y, 'w': 4}
    print(z)

    24. Join Strings

    If you need to join multiple strings, eventually having the same character or group of characters between them, you can use str.join() method:

    x = ['u', 'v', 'w']
    y = '-*-'.join(x)
    print(y)

    25. Advance Iteration

    If you want to iterate through a sequence and you need both sequence elements and the corresponding indices, you should use enumerate:

    for i, item in enumerate(['u', 'v', 'w']):
        print('index:', i, 'element:', item)

    In each iteration, you’ll get a tuple with the index and corresponding element of the sequence.

    26. Reversed Iteration

    If you want to iterate through a sequence in the reversed order, you should use reversed:

    for item in reversed(['u', 'v', 'w']):
        print(item)

    27. Aggregate Elements

    If you’re going to aggregate the elements from several sequences, you should use zip:

    x = [1, 2, 4]
    y = ('u', 'v', 'w')
    z = zip(x, y)
    print(z)
    
    print(list(z))

    28. Transpose Matrices

    Although people usually apply NumPy (or similar libraries) when working with matrices, you can obtain the transpose of a matrix with zip:

    x = [(1, 2, 4), ('u', 'v', 'w')]
    y = zip(*x)
    z = list(y)
    print(z)

    29. Unique Values

    You can remove duplicates from a list, that is obtained unique values by converting it to a set if the order of elements is not important:

    x = [1, 2, 1, 4, 8]
    y = set(x)
    print(y)
    z = list(y)
    print(z)

    30. Sort Sequences

    Sequences are sorted by their first elements by default:

    x = (1, 'v')
    y = (4, 'u')
    z = (2, 'w')
    print(sorted([x, y, z]))

    However, if you want to sort them according to their second (or other) elements, you can use the parameter key and an appropriate lambda function as the corresponding argument:

    x = (1, 'v')
    y = (4, 'u')
    z = (2, 'w')
    print(sorted([x, y, z], key=lambda item: item[1]))

    It’s similar if you want to obtain the reversed order:

    x = (1, 'v')
    y = (4, 'u')
    z = (2, 'w')
    print(sorted([x, y, z], key=lambda item: item[1], reverse=True))

    31. Sort Dictionaries

    You can use a similar approach to sort key-value tuples of dictionaries obtained with .items() method:

    x = {'u': 4, 'w': 2, 'v': 1}
    print(sorted(x.items()))

    They are sorted according to the keys. If you want to them to be sorted according to their values, you should specify the arguments that correspond to key and eventually reverse:

    x = {'u': 4, 'w': 2, 'v': 1}
    print("1:",sorted(x))
    print("2:",sorted(x.items()))
    print("3:",sorted(x.items(), key=lambda item: item[0]))
    print("4:",sorted(x.items(), key=lambda item: item[1]))
    print("5:",sorted(x.items(), key=lambda item: item[1], reverse=True))

    32. Raw Formatted Strings

    PEP 498 (Python Enhancement Proposals) and Python 3.6 introduced so-called formatted strings or f-strings. You can embed expressions inside such strings. It’s possible and straightforward to treat a string as both raw and formatted. You need to include both prefixes: fr.

    print(fr'u \ n v w={2 + 8}')
    print('u \\ n v w=10')

    33. Obtain Current Date and Time

    Python has a built-in module datetime that is versatile in working with dates and times. One of its methods, .now(), returns the current date and time:

    import datetime
    print(datetime.datetime.now())
    d = datetime.datetime(2022, 5, 20, 1, 12, 31, 230217)
    print(d)
    print(datetime.datetime.now())

    34. Obtain the Index of the Maximal (or Minimal) Element

    Python doesn’t provide a routine to directly get the index of the maximal or minimal element in a list or tuple. Fortunately, there are (at least) two elegant ways to do so:

    x = [2, 1, 4, 16, 8]
    print(max((item, i) for i, item in enumerate(x))[1])

    If there are two or more elements with the maximal value, this approach returns the index of the last one:

    y = [2, 1, 4, 8, 8]
    print(max((item, i) for i, item in enumerate(y))[1])

    To get the index of the first occurrence, you need to change the previous statement slightly:

    y = [2, 1, 4, 8, 8]
    print(-max((item, -i) for i, item in enumerate(y))[1])

    The alternative way is probably more elegant:

    x = [2, 1, 4, 16, 8]
    print(max(range(len(x)), key=lambda i: x[i]))
    y = [2, 1, 4, 8, 8]
    print(max(range(len(y)), key=lambda i: x[i]))

    To find the index of the minimal element, use the function min instead of max.

    19. Obtain the Cartesian Product

    The built-in module itertools provides many potentially useful classes. One of them is a product used to obtain the Cartesian product:

    import itertools
    x, y, z = (2, 8), ['u', 'v', 'w'], {True, False}
    print(list(itertools.product(x, y, z)))

    20. The Operator for Matrix Multiplication

    PEP 465 (Python Enhancement Proposals) and Python 3.5 introduced the dedicated infix operator for matrix multiplication @. You can implement it for your class with the methods matmul, rmatmul, and imatmul. This is how elegant the code for multiplying vectors or matrices looks like:

    import numpy as np
    x, y = np.array([1, 3, 5]), np.array([2, 4, 6])
    z = x @ y
    print(z)

    Offizielle Dokumentation

  • https://docs.python.org/3/ Die offizielle Dokumentation
  • https://docs.python.org/3/tutorial/index.html Tutorial
  • https://docs.python.org/3/howto/index.html How-To
  • Interne Dokumentation

    # Ausgabe der Liste aller Instanzen vom Typ Liste zeichnen sich durch das gleiche Interface aus:
    for i in dir([]):
      print(i)

    Ausgabe:

    # Hinweis
    ['__add__',
     '__class__',
     '__contains__',
     '__delattr__',
     '__delitem__',
     '__dir__',
     '__doc__',
     '__eq__',
     '__format__',
     '__ge__',
     '__getattribute__',
     '__getitem__',
     '__gt__',
     '__hash__',
     '__iadd__',
     '__imul__',
     '__init__',
     '__init_subclass__',
     '__iter__',
     '__le__',
     '__len__',
     '__lt__',
     '__mul__',
     '__ne__',
     '__new__',
     '__reduce__',
     '__reduce_ex__',
     '__repr__',
     '__reversed__',
     '__rmul__',
     '__setattr__',
     '__setitem__',
     '__sizeof__',
     '__str__',
     '__subclasshook__',
     'append',
     'clear',
     'copy',
     'count',
     'extend',
     'index',
     'insert',
     'pop',
     'remove',
     'reverse',
     'sort']
    # Ausgabe der Liste aller Methoden vom Typ Integer:
    for i in dir(1):
      print(i)

    Ausgabe:

    # Hinweis
    ['__abs__',
     '__add__',
     '__and__',
     '__bool__',
     '__ceil__',
     '__class__',
     '__delattr__',
     '__dir__',
     '__divmod__',
     '__doc__',
     '__eq__',
     '__float__',
     '__floor__',
     '__floordiv__',
     '__format__',
     '__ge__',
     '__getattribute__',
     '__getnewargs__',
     '__gt__',
     '__hash__',
     '__index__',
     '__init__',
     '__init_subclass__',
     '__int__',
     '__invert__',
     '__le__',
     '__lshift__',
     '__lt__',
     '__mod__',
     '__mul__',
     '__ne__',
     '__neg__',
     '__new__',
     '__or__',
     '__pos__',
     '__pow__',
     '__radd__',
     '__rand__',
     '__rdivmod__',
     '__reduce__',
     '__reduce_ex__',
     '__repr__',
     '__rfloordiv__',
     '__rlshift__',
     '__rmod__',
     '__rmul__',
     '__ror__',
     '__round__',
     '__rpow__',
     '__rrshift__',
     '__rshift__',
     '__rsub__',
     '__rtruediv__',
     '__rxor__',
     '__setattr__',
     '__sizeof__',
     '__str__',
     '__sub__',
     '__subclasshook__',
     '__truediv__',
     '__trunc__',
     '__xor__',
     'bit_length',
     'conjugate',
     'denominator',
     'from_bytes',
     'imag',
     'numerator',
     'real',
     'to_bytes']

    Spezielle Module

    1. Pandas (Panel Data)
    2. CSV-Listen (comma separated values)


    Erste Einheit: 01 Variablen