简体   繁体   中英

Portion of code running only in the first iteration through a for loop in python

So I have this code. But it runs correctly only for the first iteration through. On the second iteration, the inner for loop is not initiated. Ideas why?

Extra info if it helps: d is a DictReader object, searchtermslist is a list of strings. When I write a print line at Point 1, it prints every time I would expect it to. But a print line at point 2 prints when termindex=0 but not any other time. Let me know if you need anything else.

Thanks in advance, D

searchsums=[]
for termindex, term in enumerate(searchtermslist):
    #Point 1
    searchnumbers=[]
    for indiv_dict in d:
        #point 2
        val=indiv_dict[term]
        result=str(val)
        numbler=float(result)
        searchnumbers.append(numbler)
    if termindex==0:
        searchsums=searchnumbers[:]
    else:
        map(sum,zip(searchsums,searchnumbers))

Your first loop iteration consumes d , leaving it unavailable for subsequent iterations. Read it into a list or tuple before trying to use it.

If d is a csv.DictReader object, then when you iterate over it, it reads lines from a CSV file until the file is exhausted (ie End-of-file). Attempting to iterate over a second time will produce no results because the file is already at end-of-file.

You need to return to the beginning of the file. For example, if you created d like this:

>>> myfile = open('name_of_csv_file.csv', 'r')
>>> d = csv.DictReader(myfile)

then you can return to the beginning of the file like this:

>>> myfile.seek(0)

You could directly write:

searchnumbers.append(float(str(indiv_dict[term])))

Though it seems weird to apply str on something and then to be obliged to apply float

Wouldn't indiv_dict[term] be a float itself ?

.

I think that your problem is due to the fact that d acts as an iterator: once it has been read one time, it is exhausted and doesn't produce data anymore

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