Entfernen eines Elements aus der Liste matching-substring
Wie Entferne ich ein element aus einer Liste, wenn es einem Teilstring?
Ich habe versucht, das entfernen Sie ein element aus einer Liste mit der pop()
und enumerate
Methode, aber scheint, wie ich ' m fehlen ein paar zusammenhängende Elemente, die entfernt werden muss:
sents = ['@$\tthis sentences needs to be removed', 'this doesnt',
'@$\tthis sentences also needs to be removed',
'@$\tthis sentences must be removed', 'this shouldnt',
'# this needs to be removed', 'this isnt',
'# this must', 'this musnt']
for i, j in enumerate(sents):
if j[0:3] == "@$\t":
sents.pop(i)
continue
if j[0] == "#":
sents.pop(i)
for i in sents:
print i
Ausgabe:
this doesnt
@$ this sentences must be removed
this shouldnt
this isnt
#this should
this musnt
Gewünschte Ausgabe:
this doesnt
this shouldnt
this isnt
this musnt
InformationsquelleAutor der Frage alvas | 2012-10-01
Schreibe einen Kommentar Antworten abbrechen
Du musst angemeldet sein, um einen Kommentar abzugeben.
Wie wäre es mit etwas einfaches, wie:
InformationsquelleAutor der Antwort D.Shawley
Sollte dies funktionieren:
Wenn Sie möchten, dass nur die Dinge, die beginnen mit den angegebenen rechtskräftig festgestellten verwenden Sie die
str.startswith(stringOfInterest)
MethodeInformationsquelleAutor der Antwort mjgpy3
Anderen Technik, mit
filter
Sich das problem mit dem orignal Ansatz ist, wenn Sie auf einen Listeneintrag
i
und bestimmen, es sollte gelöscht werden, entfernen Sie Sie aus der Liste, die Folien deri+1
Element in deri
position. Die nächste iteration der Schleife bist du bei indexi+1
aber der Artikel ist eigentlichi+2
.Sinn?
InformationsquelleAutor der Antwort cod3monk3y