badbatchcoder
Goto Top

Python - In Liste nach Objekt suchen

Hey zusammen,

ich bin ein Python-Anfänger und habe eine kleine Funktion geschrieben, mit der sich Objekte in Listen suchen lassen.
Vielleicht fängt jemand auch gerade erst mit Python an und kann das hier gebrauchen:
# Searches for an object in a list and returns its position in the list
# Sucht in einer Liste nach einem Objekt und gibt dessen Position in der Liste zurück
def listfind(list, search_criterion):
    counter = 0
    element = ""  
    while element != search_criterion:
        element = list[counter]
        counter += 1
    return counter - 1
Beispiel:
print(listfind([5, 6, 1, 7.65, "hallo", [1, 2], 3, "text", 1, 2], 1))  
Konsolenausgabe: 2 --> weil sich int(1) in der Liste an zweiter Position befindet

Falls man von rechts suchen möchte, kann man folgende Funktion benutzen:
# Searches for an object in a list from right to left and returns its position (from the left)
# Sucht von rechts nach links in einer Liste nach einem Objekt und gibt dessen Position zurück (von links)
def rlistfind(list, search_criterion):
    counter = len(list) - 1
    element = ""  
    while element != search_criterion:
        element = list[counter]
        counter -= 1
    return counter + 1
Beispiel:
print(rlistfind([5, 6, 1, 7.65, "hallo", [1, 2], 3, "text", 1, 2], 1))  
Konsolenausgabe: 8 --> weil sich int(1) in der Liste von rechts nach links gesucht an achter Positon befindet
Falls man die Position von rechts aus haben will, kann man die Funktion auch folgendermaßen aufrufen:
list = [5, 6, 1, 7.65, "hallo", [1, 2], 3, "text", 1, 2]  
print(len(list) - rlistfind(list, 1))
(Hierbei wird einfach nur die Länge der Liste von der Position des Objekts (von links aus) abgezogen)

Ich hoffe mein Beitrag hat jemandem weitergeholfen!
LG BadBatchCoder

Content-Key: 1153114099

Url: https://administrator.de/contentid/1153114099

Printed on: April 26, 2024 at 13:04 o'clock

Mitglied: 149062
149062 Aug 13, 2021 updated at 17:45:00 (UTC)
Goto Top
Zur Info
list = [5, 6, 1, 7.65, "hallo", [1, 2], 3, "text", 1, 2]  
print(list.index("hallo"))  
https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.