I've been struggling for the past day to solve a very simple (but frustratingly difficult) problem. I currently have a piece of code which uses csv reader to loop through csv files row by row. The loop is not an issue as I've used the same one before with success; it seems to be an issue with my if statements.
Here is a sample:
if 'INCORRECT_KEY_PRESSED' and 'rad_mod_KA_0043-lo-mod' in row:
userAnswerColumn.append(row[20])
userRtColumn.append(row[21])
This statement is supposed to append two lists with values from specific locations in a row, if that row contains the phrases INCORRECT_KEY_PRESSED and rad_mod_KA_0043-lo-mod. I have several such statements, but a row never has both of these phrases more than once. Phrases like rad_mod_KA_0043-lo-mod are always unique, while INCORRECT_KEY_PRESSED occurs many times.
It seems that the if statement is only using one of my conditions, as it is appending more than one piece of data to each list.
I've had this problem in the past and solved it by creating sets and doing something like this:
if (all(x in row for x in ssSet) and row[14] == '7'):
ssColumn7.append(row[20])
ssRtColumn7.append(row[21])
However, there are so many unique terms that I would have to make a plethora of sets. What's going wrong?
-
Not sure why this is getting downvoted, it shows research effort and it's a common mistake.japreiss– japreiss2012年11月08日 15:51:59 +00:00Commented Nov 8, 2012 at 15:51
3 Answers 3
The statement 'INCORRECT_KEY_PRESSED' and 'rad_mod_KA_0043-lo-mod' in row is interpreted as:
('INCORRECT_KEY_PRESSED') and ('rad_mod_KA_0043-lo-mod' in row)
The first part is always True (non-empty strings are 'truthy', or considered boolean True in a boolean expression).
You probably wanted:
if 'INCORRECT_KEY_PRESSED' in row and 'rad_mod_KA_0043-lo-mod' in row:
instead, or you could use set intersections:
if {'INCORRECT_KEY_PRESSED', 'rad_mod_KA_0043-lo-mod'}.intersection(row):
Your grouping is wrong, python works like:
if ('INCORRECT_KEY_PRESSED') and ('rad_mod_KA_0043-lo-mod' in row):
so you need:
if ('INCORRECT_KEY_PRESSED' in row) and ('rad_mod_KA_0043-lo-mod' in row):
Comments
if 'INCORRECT_KEY_PRESSED' and 'rad_mod_KA_0043-lo-mod' in row:
userAnswerColumn.append(row[20])
userRtColumn.append(row[21])
should be changed to :
if ('INCORRECT_KEY_PRESSED' in row) and ('rad_mod_KA_0043-lo-mod' in row):
userAnswerColumn.append(row[20])
userRtColumn.append(row[21])
because otherwise python understands
if ('INCORRECT_KEY_PRESSED') and 'rad_mod_KA_0043-lo-mod' in row:
which is probably always true.
You may want to think about that each time you have multiple conditions to test.