75 lines
1.7 KiB
Python
75 lines
1.7 KiB
Python
li = [1, 3, 2, 6, 7, 3, 4, 3, 2, 5]
|
|
|
|
# 1.) Gerade Zahlen aus einer Liste extrahieren
|
|
|
|
# Aufgabe: Eine Liste mit allen geraden Zahlen zurückgeben
|
|
|
|
# a) for loop
|
|
def even_num_for(li):
|
|
even_list = []
|
|
|
|
for i in li:
|
|
if i % 2 == 0:
|
|
even_list.append(i)
|
|
return even_list
|
|
|
|
# b) lambda function with filter
|
|
def even_num_lambda(li):
|
|
return list(filter(lambda i: i % 2 == 0, li))
|
|
|
|
# c) list comprehension
|
|
def even_num_list_comprehension(li):
|
|
return [i for i in li if i % 2 == 0]
|
|
|
|
# d) while loop
|
|
def even_num_while(li):
|
|
i = 0
|
|
even_list = []
|
|
while i < len(li):
|
|
if li[i] % 2 == 0:
|
|
even_list.append(li[i])
|
|
i += 1
|
|
return even_list
|
|
|
|
print(f"1. a) {even_num_for(li)}") # a)
|
|
print(f"1. b) {even_num_lambda(li)}") # b)
|
|
print(f"1. c) {even_num_list_comprehension(li)}") # c)
|
|
print(f"1. d) {even_num_while(li)}") # d)
|
|
|
|
# 2.) Elemente umwandeln
|
|
|
|
# Aufgabe: Alle Elemente der Liste li in den Typ str umwandeln
|
|
|
|
# a) for loop
|
|
def to_string_for(li):
|
|
string_list = []
|
|
for i in li:
|
|
string_list.append(str(i))
|
|
return string_list
|
|
|
|
# b) lambda function
|
|
def to_string_lambda(li):
|
|
return list(map(lambda i: str(i), li))
|
|
|
|
# c) lambda function
|
|
def to_string_map(li):
|
|
return list(map(str, li))
|
|
|
|
# d) lsit comprehension
|
|
def to_string_list_comprehension(li):
|
|
return [str(i) for i in li]
|
|
|
|
# e) lsit comprehension
|
|
def to_string_while(li):
|
|
i = 0
|
|
string_list = []
|
|
while i < len(li):
|
|
string_list.append(str(li[i]))
|
|
i += 1
|
|
return string_list
|
|
|
|
print(f"2. a) {to_string_for(li)}") # a)
|
|
print(f"2. b) {to_string_lambda(li)}") # b)
|
|
print(f"2. c) {to_string_map(li)}") # c)
|
|
print(f"2. d) {to_string_list_comprehension(li)}") # d)
|
|
print(f"2. e) {to_string_while(li)}") # e) |