using a for loop to compare lists

111 views Asked by At

The problem at hand is I have a list of lists that I need to iterate through and compare one by one.

def stockcheck():
    stock = open("Stock.csv", "r")
    reader = csv.reader(stock)
    stockList = []
    for row in reader:
        stockList.append(row)

The output from print(stockList) is:

[['Product', 'Current Stock', 'Reorder Level', 'Target Stock'], ['plain blankets', '5', '10', '50'], ['mugs', '15', '20', '120'], ['100m rope', '60', '15', '70'], ['burner', '90', '20', '100'], ['matches', '52', '10', '60'], ['bucket', '85', '15', '100'], ['spade', '60', '10', '65'], ['wood', '100', '10', '200'], ['sleeping bag', '50', '10', '60'], ['chair', '30', '10', '60']]

I've searched the basics for this but i've had no luck... I'm sure the solution is simple but it's escaping me! Essentially I need to check whether the current stock is less than the re-order level, and if it is save it to a CSV (that part I can do no problem).

for item in stockList:
    if stockList[1][1] < stockList[1][2]:
        print("do the add to CSV jiggle")

This is as much as I can do but it doesn't iterate through... Any ideas? Thanks in advance!

2

There are 2 answers

3
AudioBubble On BEST ANSWER

Iterate through the stockList using list comprehension, maybe and then print out the results

[sl for sl in stockList[1:] if sl[1] < sl[2]]

You will get the following results:

[['mugs', '15', '20', '120']]

In case you were wondering stockList[1:] is to ensure that you ignore the header.

However, you must note that the values are strings that are being compared. Hence, the values are compared char by char. If you want integer comparisons then you must convert the strings to integers, assuming you are absolutely sure that sl[1] and sl[2] will always be integers - just being presented as strings. Just try doing:

[sl for sl in stockList[1:] if int(sl[1]) < int(sl[2])]

The result changes:

[['plain blankets', '5', '10', '50'], ['mugs', '15', '20', '120']]
2
Avión On

Use the [1:] to not get the header, and then make the comparation.

for item in stockList[1:]:
    if item[1] < item[2]:
        print item
        print("do the add to CSV jiggle")