简体   繁体   中英

for and if/else loop with nested if statement not working in python

Below is my code to separate my lists into lists of lists, followed by printing the word 'hello' if values in these lists match... However I'm having some problems getting this to work. As far as I know, all syntax is correct, its just the output that won't work.

import csv
import operator
import itertools
import matplotlib.pyplot as plt

with open('data.txt', 'r') as f:
    csv_input = csv.reader(f, delimiter=' ', skipinitialspace=True)
    headers = next(csv_input)

    counter = 0
    i = 1

    for k, g in itertools.groupby(csv_input,key=operator.itemgetter(3)):
        row = []
        for entry in g:
            entry = [float(e) for e in entry]
            row.append(entry)
        counter = counter+1
        i = i+1
        #print(row)  #(not necessary to see the results hence commented out)
        if counter == 1: 
            row1 = row
        else:
            row2 = row
            for i in range(1, len(row1)):          
                hi = row1[i][0]
            for j in range(1,len(row2)):
                if row2[j][0] == hi:      #this clause doesnt work
                    print('hello')
            counter=1 
            row1=row

What I'm doing here is comparing the 1st value from the first list, with the 2nd value from the first line of the next list. Then, I want to compare the 1st value from first line of the second list, with the first line of the next list, and so on... (I know this seems quite confusing!), and if these values are the same, then it will plot a line, but for simplicity, lets just say it will print('hello'), as the code works up until where it is marked '#this clause doesnt work'

Any help would be greatly appreciated! Thanks in advance

Then, I want to compare the 1st value from first line of the second list, with the first line of the next list, and so on...

Sounds like you want to iterate over i and j at the same time. Right now, you're iterating over i , then stopping, then iterating over j . Try using zip .

Replace

        for i in range(1, len(row1)):          
            hi = row1[i][0]
        for j in range(1,len(row2)):
            if row2[j][0] == hi:
                print('hello')

With

        for i, j in zip(range(1, len(row1)), range(1,len(row2))): 
            hi = row1[i][0]
            if row2[j][0] == hi:
                print('hello')

Also, not sure if this was intentional or not - starting the range at 1 means that you start looking at the second element of each list, rather than the first. Use range(len(row1)) and range(len(row2)) if you want to iterate over the complete lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM