Dies ist die Support Website des Buches:
Das Python Praxisbuch
Der große Profi-Leitfaden für Programmierer
Farid Hajji
Addison Wesley / Pearson Education
ISBN 978-3-8273-2543-3 (Sep 2008), 1298 Seiten.
6. Listen¶
URLs:
- Der C++ Datentyp std::vector (ähnlich zum Python Datentyp
list
)
Zugriff auf Listenelemente¶
Listen-Slices¶
Memberfunktionen von Listen¶
Screenshots:
#!/usr/bin/env python
# allindex.py -- an iterated list.index function.
def allindex(the_list, the_value):
"Compute a list of all indexes of the_value within the_list."
indexes = []
try:
search_from_here = 0
while True:
found_index = the_list.index(the_value, search_from_here)
indexes.append(found_index)
search_from_here = found_index + 1
except ValueError:
return indexes
if __name__ == '__main__':
assert allindex([111, 222, 333, 222, 444, 555], 222) == [1, 3]
assert allindex([111, 222, 333, 222, 444, 555], 999) == []
assert allindex([], 111) == []
Anwendungen¶
Listen durchlaufen¶
Listen kopieren und vergleichen¶
Skizzen:
Listen sortieren¶
#!/usr/bin/env python
# listsortci.py -- sort list case-insensitively
def ci_compare(x, y):
"Compare two strings case-insensitively"
return cmp(x.lower(), y.lower())
def ci_compare_verbose(x, y):
"Compare two strings case-insensitively"
x_lower, y_lower = x.lower(), y.lower()
if x_lower < y_lower: return -1
elif x_lower > y_lower: return 1
else: return 0
L = 'The Quick Brown Fox Jumped over the Lazy Dog'.split()
L1, L2, L3, L4, L5 = L[:], L[:], L[:], L[:], L[:] # Create copies of L
L1.sort(cmp=ci_compare)
L2.sort(cmp=ci_compare_verbose)
L3.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
L4.sort(key=str.lower)
L5.sort(key=lambda x: x.lower())
print L1
print L2
print L3
print L4
print L5
# Output in all five cases:
# ['Brown', 'Dog', 'Fox', 'Jumped', 'Lazy', 'over', 'Quick', 'The', 'the']
Sortieren von Klasseninstanzen¶
Die modifizierte Klasse Employee
:
class Employee(object):
"The classic employee"
def __init__(self, lastname, middlename, firstname):
self.lastname = lastname
self.middlename = middlename
self.firstname = firstname
def __repr__(self):
return '<Employee "%s %s. %s">' % (self.firstname,
self.middlename,
self.lastname)
def __cmp__(self, other):
if self.lastname < other.lastname: return -1
elif self.lastname > other.lastname: return 1
elif self.firstname < other.firstname: return -1
elif self.firstname > other.firstname: return 1
else: return 0 # We don't care about middlenames
List comprehensions¶
Stabiles Sortieren¶
URLs:
- Wann ist ein Sortieralgorithmus stabil? (vgl. dort das “Stable”-Kriterium in den Tabellen)