[Tutor] partial string matching in list comprehension?
Kent Johnson
kent37 at tds.net
Fri May 26 12:47:15 CEST 2006
Wolfram Kraus wrote:
> doug shawhan wrote:
>> I have a series of lists to compare with a list of exclusionary terms.
>>
>>
>>
>> junkList =["interchange", "ifferen", "thru"]
>>
>> The comparison lists have one or more elements, which may or may not
>> contain the junkList elements somewhere within:
>>
>> l = ["My skull hurts", "Drive the thruway", "Interchangability is not my
>> forte"]
>>
>> ... output would be
>>
>> ["My skull hurts"]
>>
>> I have used list comprehension to match complete elements, how can I do
>> a partial match?
>>
>> def removeJunk(reply, junkList):
>> return [x for x in reply if x not in junkList]
>>
>> It would be so much prettier than searching through each list element
>> for each term - I tend to get lost in a maze of twisty corridors, all alike.
>>
>> Thanks!
>>
>>
> Dunno if the performance of this solution is good and if it is more
> readable then RegExps, but here is LC:
> [x for x in l if not [j for j in junkList if x.lower().find(j) > -1]]
A little cleaner is
[ j for j in junkList if j not in x.lower() ]
This will compute x.lower() for each element of junkList...
Kent
>
> >>> l = ["My skull hurts", "Drive the thruway", "Interchangability is
> not my forte"]
> >>> junkList =["interchange", "ifferen", "thru"]
> >>> [x for x in l if not [j for j in junkList if x.lower().find(j) > -1]]
> ['My skull hurts', 'Interchangability is not my forte']
> ^ Is there an "e" missing?
>
> Because I don't like RegExps! ;-)
>
> HTH,
> Wolfram
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
More information about the Tutor
mailing list