list comprehensions¶
Mit list comprehensions ist es Möglich einfache for-loops als Einzeiler zu schreiben. Die erzeugte Liste wird im Speicher gehalten. Aus 3 wesentlichesn Komponenten besteht eine list comprehensions:
- Iterable
- Iterator Variable
- Ausgabe Anweisung
Basic:
[output expression for iterator variable in iterable]
Advanced:
[output expression + condition for iterator variable in iterable + condition]
for - loop¶
In [6]:
nums = [4,7,22,9]
numsPlusOne = []
for num in nums:
numsPlusOne.append(num + 1)
print(numsPlusOne)
for - loop in list comprehensions style¶
In [17]:
nums = [4,7,22,9]
numsPlusOne = [num + 1 for num in nums]
print(numsPlusOne)
nested list comprehensions¶
In [26]:
matrix = [[col + row for col in range(5)] for row in range (5)]
for row in matrix:
print(row)
conditionals in comprehensions¶
In [30]:
mylist = [num for num in range(10) if num % 2 ==0]
print(mylist)
conditionals in comprehensions on the output expression¶
In [37]:
mylist = [num if num % 2 == 0 else '-' for num in range(10)]
print(mylist)
list comprehensions for list of tuples¶
In [67]:
myListOfTuples = [('A1','A2','A3'),('B1','B2','B3')]
newList = [val1 + val2 + val3 for val1,val2,val3 in myListOfTuples]
print(newList)
newList = [tup[0] + tup[1] + tup[2] for tup in myListOfTuples]
print(newList)
dict comprehensions¶
In [40]:
myDict = {key: key * 2 for key in range(10)}
print(myDict)
generators¶
Sehr ähnlich wie list comprehensions jedoch mit () statt [].
Die erzeugte Liste wird jedoch nicht komplett im Speicher gehalten. Sondern erst für jede einzelne Iteration on the fly generiert.
In [48]:
myGenerator = (len(val) for val in ['a','aa','aaa'])
print(myGenerator)
print(list(myGenerator))
generator function¶
In [53]:
my_list = ['a','aa','aaa']
def get_lengths(input_list):
for value in input_list:
yield len(value)
print(get_lengths(my_list))
print(list(get_lengths(my_list)))