0

I have a csv file with the following data:

Rectangle   Green   Large
Rectangle   Green   Large
Rectangle   Green   Small
Rectangle   Green   Medium
Rectangle   Green   Small
Rectangle   Blue    Large
Rectangle   Blue    Large
Rectangle   Blue    Medium
Rectangle   Orange  Large
Circle  Pink    Small
Circle  Pink    Small
Circle  Green   Large
Circle  Green   Large

and my code for Python is the following:

import csv

with open("shapes.csv", 'rb') as csvfile:
    rowreader = csv.reader(csvfile, quotechar = '|')
    for row in rowreader:
        if 'Large' and 'Green' in row:
            print row

However the output I get is:

['Rectangle', 'Green', 'Large']
['Rectangle', 'Green', 'Large']
['Rectangle', 'Green', 'Small']
['Rectangle', 'Green', 'Medium']
['Rectangle', 'Green', 'Small']
['Circle', 'Green', 'Large']
['Circle', 'Green', 'Large']

I am trying to only display the records where Green and Large are in the row. Everything else should be excluded. I thought 'and' would complete this but it seems I am confused and going in the wrong direction.

What would be the correct way to implement this?

  • Possible duplicate of [Can Python test the membership of multiple values in a list?](http://stackoverflow.com/questions/6159313/can-python-test-the-membership-of-multiple-values-in-a-list) – Ankit Jaiswal Mar 11 '16 at 09:46

4 Answers4

0

It should be

if 'Large' in row and 'Green' in row:
aadarshsg
  • 2,069
  • 16
  • 25
0
>>> "Large" and "Green" in row

is interpreted as "Large" and ("Green" in row) which is always true.

>>> ("Large" in row) and ("Green" in row)

would work and is simple enough if you have only two items. Otherwise, I would use

>>> set(["Large", "Green"]).issubset(set(row))
kmario23
  • 57,311
  • 13
  • 161
  • 150
Arnaud
  • 750
  • 10
  • 25
0

You are actually testing two different things in here:

if ('Large' (== True)) and ('Green' in row):

Doing 'Large' == True is always true since it is a literal string, so you are actually printing all the lines that contain the word 'Green', because the other half is always true.

if 'Large' in row and 'Green' in row:

will do the what you want.

kmario23
  • 57,311
  • 13
  • 161
  • 150
randombee
  • 699
  • 1
  • 5
  • 26
0

You might want to be more specific about into what column you look for what value.

For example this:

if row[1] == 'Green' and row[2] == 'Large':

would make sure that the color is always checked in the second column and size is always checked for in the third column.

kmario23
  • 57,311
  • 13
  • 161
  • 150
Mike Müller
  • 82,630
  • 20
  • 166
  • 161