Hör zu#
Oft wollen wir auf viele ähnliche Elemente gleichzeitig zugreifen, z.B. Monate:
Suppose we want to store the average monthly temperatures in a city and have measured the following data:
jan = 1.9
feb = 2.5
mar = 5.9
apr = 10.3
mai = 14.6
jun = 18.1
jul = 20
aug = 19.6
sep = 15.7
okt = 10.9
nov = 6.2
dez = 2.8
If the data is to be further processed, it becomes very impractical because we have to “touch” each individual value every time. Therefore, lists are used instead.
Therefore, lists are used for this purpose, where similar elements are grouped under a common name and can be accessed using an index.
What are lists?#
Lists sind eine Zusammenfassung von Daten, bei der jedes Datum durch einen Index identifiziert wird. Die einzelnen Werte einer Liste nennt man Elemente.
Listen erstellen#
In Python kann man Listen auf verschiedene Arten und Weisen erzeugen. Die einfachste Möglichkeit ist es, Listen mit Hilfe von eckigen Klammern zu erzeugen:
l = [1, 2, 3]
l = ["mini", "worlds"]
Listen können selbst unterschiedliche Datentypen enthalten, d.h. auch dies ist eine Liste:
l = ["hi", 1, 2, [3, 4]]
As you can see, it is even possible (and often necessary) to create a list within a list.
Length einer Liste#
You can calculate the length of a list with the function len():
print(len([1, 2, 3])) # 3
print(len(["mini", "worlds"])) # 2
Access elements#
Using the index
, you can access elements of a list. The syntax for this is as follows
variable_name[index]
z.B.
numbers = [2, 4, 8, 16, 32]
print(numbers[0]) # 2
print(numbers[2]) # 8
print(numbers[3]) # 16
Listenelemente ändern#
You can also change list elements using the index:
numbers = [2, 4, 8, 16, 32]
numbers[0] = 1
print(numbers) # [1, 4, 8, 16, 32]
append()#
Listen in Python haben eine dynamische Größe und können verändert werden. So kannst du jederzeit mit append() ein Element an eine Liste anhängen:
numbers = [2, 4, 8, 16, 32]
numbers.append(64)
print(numbers) # [2, 4, 8, 16, 32, 64]
in#
Mit dem Schlüsselwort in
kannst du überprüfen, ob ein Element in einer Liste enthalten ist.
numbers = [2, 4, 8, 16, 32]
print(2 in numbers) # True
print(3 in numbers) # False
This is a significant difference from other programming languages that know arrays as a data structure instead of lists. Arrays are immutable and have a fixed length.
Example : Monate#
Anhand des Beispiels der Monate schauen wir uns dies nochmal genauer an. Anstelle von einzelnen Variablen kann man die Monate als Liste anlegen:
months = []
months.append(1.9)
months.append(2.5)
months.append(5.9)
months.append(10.3)
months.append(14.6)
months.append(18.1)
months.append(20)
months.append(19.6)
months.append(15.7)
months.append(10.9)
months.append(6.2)
months.append(2.8)
Alternativ könnte man die Liste auch so anlegen:
months = [1.9, 2.5, 5.9, 10.3, 14.6, 18.1, 20, 19.6, 15.7, 10.9, 6.2, 2.8]
Wenn wir die Liste ausgeben, erhalten wir folgendes:
print(months)
> [1.9, 2.5, 5.9, 10.3, 14.6, 18.1, 20, 19.6, 15.7, 10.9, 6.2, 2.8]
We can access the individual list elements with an index:
print(months[1], months[4])
> 2.5 14.6
And we can iterate over the list with a loop. This way, we can calculate the average temperature, for example:
for month in months:
sum = sum + month
print(sum/12) # output 10.708
We can use this to visualize the data:
from miniworlds import *
world = World(400, 240)
months = []
months.append(1.9)
months.append(2.5)
months.append(5.9)
months.append(10.3)
months.append(14.6)
months.append(18.1)
months.append(20)
months.append(19.6)
months.append(15.7)
months.append(10.9)
months.append(6.2)
months.append(2.8)
i = 0
for month in months:
Rectangle((0,i), month * 10, 20)
n = Number((200,i), month)
n.font_size = 10
i = i + 20
world.run()
Save graphic objects#
We can also store objects in arrays. This is often needed for collision detection, for example.
Zum Beispiel wollen wir ein Programm schreiben, bei dem grüne Kreise eingesammelt und rote Punkte vermieden werden sollen. Dies können wir folgendermaßen mit Listen umsetzen:
from miniworlds import *
import random
world = World(400, 200)
points = Number((0,0), 0)
red_circles = []
green_circles = []
@world.register
def act(self):
if self.frame % 100 == 0:
c = Circle((400, random.randint(0,200), 40))
c.color = (255, 0, 0)
red_circles.append(c)
elif self.frame % 50 == 0:
c = Circle((400, random.randint(0,200), 40))
c.color = (0, 255, 0)
green_circles.append(c)
for circle in red_circles:
circle.move_left()
for circle in green_circles:
circle.move_left()
@world.register
def on_mouse_left(self, mouse_position):
actors = self.get_actors_at_position(mouse_position)
for actor in actors:
if actor in red_circles:
actor.remove()
points.set_number(points.get_number() - 1)
elif actor in green_circles:
actor.remove()
points.set_number(points.get_number() + 1)
world.run()
When you click on the green circles, the score increases by 1, otherwise it decreases by 1.
The collision detection works with the help of lists: the circles are each added to the list red_circles and green_circles - In this way, you can check with circle in green_circles
whether a circle is contained in one of these two lists.