Reputation: 313
I am trying to compare numbers from a numbers.txt file. Whats bothering me is the negative index property in Python, where negative number actually means reading from right to left.
Is there a way to ignore just the first comparison? Where I output that there is no previous number(see desired output)
Important is that I can not change my numbers.txt file. These I get automatically generated from another function.
$ cat numbers.txt
1
2
3
4
5
code:
with open('numbers.txt') as file:
lines = file.read().splitlines()
print lines
for i in range(len(lines)):
previous_number = lines[i-1]
current_number = lines[i]
print "current Nr: ", current_number
print "previous Nr: ", previous_number
if current_number > previous_number:
print " current Nr is larger"
else:
print "current Nr is smaller"
output:
['1', '2', '3', '4', '5']
current Nr: 1
previous Nr: 5
current Nr is smaller
current Nr: 2
previous Nr: 1
current Nr is larger
current Nr: 3
previous Nr: 2
current Nr is larger
current Nr: 4
previous Nr: 3
current Nr is larger
current Nr: 5
previous Nr: 4
current Nr is larger
desired output
['1', '2', '3', '4', '5']
current Nr: 1
previous Nr: There is no previous!
current Nr is none
current Nr: 2
previous Nr: 1
current Nr is larger
current Nr: 3
previous Nr: 2
current Nr is larger
current Nr: 4
previous Nr: 3
current Nr is larger
current Nr: 5
previous Nr: 4
current Nr is larger
Upvotes: 1
Views: 452
Reputation: 12669
You can give a try this method :
with open('numbers.txt') as file:
numbers=[None,]
for line in file:
numbers.append(line)
for idx,no in enumerate(numbers,1):
try:
if numbers[idx]>numbers[idx-1]:
print('Current no is {}'.format(numbers[idx]))
print('Previous no is {}'.format(numbers[idx-1]))
print ("current Nr is larger")
else:
print ("current Nr is smaller")
except TypeError:
print('Current no is {}'.format(numbers[idx]))
print('There is no previous!')
except IndexError:
pass
output:
Current no is 1
There is no previous!
Current no is 2
Previous no is 1
current Nr is larger
Current no is 3
Previous no is 2
current Nr is larger
Current no is 4
Previous no is 3
current Nr is larger
Current no is 5
Previous no is 4
current Nr is larger
Upvotes: 1
Reputation: 585
You can use enumerate
to check on index
for i, value in enumerate(lines):
previous_number = "None"
CurrentNrText = "None"
if i != 0:
previous_number = lines[i-1]
if current_number > previous_number:
CurrentNrText = " current Nr is larger"
else:
CurrentNrText = "current Nr is smaller"
current_number = lines[i]
print("current Nr: ", current_number)
print("previous Nr: ", previous_number)
print(CurrentNrText)
Upvotes: 2
Reputation: 81594
If you want to start from the second number, then explicitly start from the second number:
for i in range(1, len(lines)):
Or, even better, use the more idiomatic enumerate
:
for i, number in enumerate(lines[1:], 1):
Upvotes: 1