Reputation: 1407
I'm reading a file line by line, and I've separated it out with line.split(',') the way I want to. Now I want to flag, copy to list, or perform a function on:
A line which contains the string 'THIS', but not 'THAT'.
I'm shooting for something that looks like this:
if any(('THIS' in s for s in csvLine) if any('THAT' **!in** s for s in csvLine):
print csvLine
but this isn't good syntax at all. I think I'm in over my head using list comprehension, but I have successfully done it before thanks to this answer.
I do have a working solution with the code below, but I sense there's something better:
if any('THAT' in s for s in csvLine):
print "do nothing"
elif any('THIS' in s for s in csvLine):
print "do something"
else:
print "do nothing"
How do I compress the logic of these if-else statements into more beautiful, pythonic, code?
This is my actual, not-generalized, plain English question: if a line contains CHAT and TRANSFER, then it is unimportant. If it contains only CHAT, it is unimportant. If it contains just TRANSFER and not the word CHAT, it is noteworthy and I want to do something with the line. How to I find the lines with the word TRANSFER, but not CHAT in them?
Upvotes: 2
Views: 4972
Reputation: 4399
From the question you linked to, make a slight modification:
csv_line = ["Has CHAT", "Has TRANSFER", "Has CHAT and TRANSFER"]
transfers = [s for s in csv_line if "TRANSFER" in s and "CHAT" not in s]
print transfers
>>> ['Has TRANSFER']
Upvotes: 1
Reputation: 599580
Not sure if I fully understand - why do you need to iterate through the line? This seems like it would work better:
if 'this' in csvLine and not 'that' in csvLine:
do_something()
Upvotes: 4
Reputation: 212855
if any('THIS' in s for s in csvLine) and all('THAT' not in s for s in csvLine):
is the same as
if any('THIS' in s for s in csvLine) and not any('THAT' in s for s in csvLine):
The 'THIS' part will stop iterating as soon as 'THIS' is found and the 'THAT' will stop iterating as soon as 'THAT' is found. It is possible, that one or both of the iterations will have to complete.
Upvotes: 1