Question

Currently, I am attempting to retrieve numeric data from different CSV files. I then place that data in lists in Python. However, I'm struggling to get Python to determine if there is a value in each separate list of data that is greater than a certain number. I need to be able to search each list separately for some value at which point Python should return some text of my choice. I'm not sure what I'm missing, but Python doesn't seem to be handling my syntax as I was hoping.

    import csv
    stocks = ['JPM','PG','KO','GOOG']
    for stock in stocks:
        Data = open("%sMin.csv" % (stock), 'r')
        Ticker = []
        for row in Data:
            Ticker.append(row.strip().split(','))
        if Ticker > 735:
            print "%s Minimum" % (stock)

I modified the code the other stock became Ticker to remove the confusion.

Was it helpful?

Solution

There are three things wrong, preventing you from getting the result.

  1. stock is a list of values, so you aren't able to directly do a numeric comparison to the list itself.
  2. You are appending lists to the list. So even if you were operating on each value you will be comparing a list to an int. Either figure out which element to append, or add them all appropriately.
  3. Find the max value in that list to compare to you int.

First, append floats to your list:

float(stock_value)

Second, figure out which index of your split row is the numeric value. If they are all numeric values, then add them all to the list by extending:

# only convert items to float that are not empty strings
stock.extend(float(val) for val in row.strip().split(',') if val.strip())

If its say, the first column, add just that one:

stock.append(float(row.strip().split(',')[0]))

Third, if you simply want to know if a value greater than 735 is in your list, you can simply ask it for the max value of the list:

if max(stock) > 735:
    print "%s Minimum" % (stock)

OTHER TIPS

Make sure you convert your stock prices to floats when adding them to the list.

stock.extend(map(float, row.strip().split(',')))

Now get on to your test.

max(stock) > 735

Should do the trick. If the largest number in the list is greater than your target, then you know at least one number is.

A more explicit way is:

any(x > 735 for x in stock)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top