简体   繁体   中英

Checking if a number in a list is bigger than the last number in the same list

I need to check if a number has increased in a list, I've tried doing this:

for x in lines:
    if(lines[x] > lines[x-1]):
        ++times_increased

but it doesn't seem to work and returns an error "list indices must be integers or slices, not str" the list is called lines because I'm getting the input data from a txt file and every line is a new number I have to compare to the last number in that file.

The loop for x in lines gives each element of the iterable lines , the elements seem to be strings.

Consider using for x in range(len(lines)) to iterate through all the indices, or the more pythonic for n,m in zip(lines, lines[1:]) , where n and m are neighboring numbers in lines.

In addition, ++times_increased does not add one to times_increased in python. Instead do times_increased = times_increased + 1 or the shorthand version times_increased += 1 .

Note that the numbers need to be transformed from strings to integers using the int-function, ie int(lines[x]) or int(n).

You can pair up each element with its successor using zip() and feed the comparisons to the sum() function (True will count as 1 and False as 0):

times_increased = sum(a<b for a,b in zip(lines,lines[1:]))

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