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.
CodePudding user response:
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, i.e int(lines[x]) or int(n).
CodePudding user response:
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:]))