Take this code for example:
import csv
with open('Airports.txt', 'r') as f:
reader = csv.reader(f)
amr_csv = list(reader)
for line in amr_csv:
print(line)
For an input of:
JFK,John F Kennedy International,5326,5486.
ORY,Paris-Orly,629,379.
MAD,Adolfo Suarez Madrid-Barajas,1428,1151.
AMS,Amsterdam Schiphol,526,489.
CAI,Cairo International,3779,3584.
The code outputs a list like so: [['JFK', 'John F Kennedy International', '5326', '5486'], ['ORY', 'Paris-Orly', '629', '379'], ['MAD', 'Adolfo Suarez Madrid-Barajas', '1428', '1151'], ['AMS', 'Amsterdam Schiphol', '526', '489'], ['CAI', 'Cairo International', '3779', '3584'], []]
So let's say when the iterator is at the second element and I want to compare its value with an element from the first element, (example: comparing ORY with JFK) what do I do? If I do a:
j = i-1
for i in line:
if i[0] != j[0]
it gives me an error:
j = i-1.
TypeError: unsupported operand type(s) for -: 'list' and 'int'.
How can I do this without an error?
CodePudding user response:
Given the input:
input = [['JFK', 'John F Kennedy International', '5326', '5486'], ['ORY', 'Paris-Orly', '629', '379'], ['MAD', 'Adolfo Suarez Madrid-Barajas', '1428', '1151'], ['AMS', 'Amsterdam Schiphol', '526', '489'], ['CAI', 'Cairo International', '3779', '3584'], []]
You can iterate the list like this:
for i in range(1, len(input)):
print(f'{input[i-1][0]}, {input[i][0]}')
This will print:
JFK, ORY
ORY, MAD
MAD, AMS
AMS, CAI
Just use the variable references for your comparison purposes and whatever instructions you need to code based on the equality result.
CodePudding user response:
I don't know of a "built-in" feature allowing one to get the "prior" item in a list. Getting it via mylist[index -1] is certainly a valid option (see answer by @cesarv: https://stackoverflow.com/a/70685822/218663) that I upvoted.
However, if it was me, I would personally be more explicit about things so that someone in the future was not potentially guessing about what I was attempting to do.
To that end, I would maintain a prior variable.
data_in = [
['JFK', 'John F Kennedy International', '5326', '5486'],
['ORY', 'Paris-Orly', '629', '379'],
['MAD', 'Adolfo Suarez Madrid-Barajas', '1428', '1151'],
['AMS', 'Amsterdam Schiphol', '526', '489'],
['CAI', 'Cairo International', '3779', '3584'],
]
prior = data_in[0]
for current in data_in[1:]:
print(f'{prior[0]}, {current[0]}')
prior = current
CodePudding user response:
for i in range(len(amr_csv)):
for j in range(len(amr_csv[i])):
# start at second element
if i:
if amr_csv[i][j] == amr_csv[i-1][j]:
# do something
pass
