简体   繁体   中英

Cannot iterate through list with for loop in python

my program uses findall function from re library to sum all the numbers in a file:

fh=open(fname)
lst=re.findall('[0-9]+',fh.read())

findall supposedly returns a list right? so i'm supposed to loop through it like this:

for i in lst :
 s=s+int(lst[i])

but i get traceback error that says:

    s=s+int(lst[i])
TypeError: list indices must be integers or slices, not str

Now it works just fine if i use range() :

for i in range(len(lst))

I just don't understand why i get this error cause list is by default indexed with integers right? can someone explain to me? thank you !

You have two ways to do it:

for i in range(len(lst)):
 s += int(lst[i])

and second:

for i in lst:
 s += int(i)

for i in lst: already takes out the elements one-by-one and you don't require to index the list. So try:

for i in lst :
    s=s+int(i)

As you are trying to get the elements out of the list, for i in lst: does that job. So for example:

lst = [1,2,3,4]
for i in lst:
    print(i)

gives the output:

1
2
3
4

i is a string, so lst[i] fails.

You could convert it to an int with lst[int(i)] , but that's not really what you're trying to do. See Joshua's answer for how to fix it.

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