Index of tuples in a list - python

Asked

Viewed 130 times

0

Organisation of information in the file

(City, City, Distance)

import csv
with open('cidades.csv', 'r') as f:
       list1 = [tuple(line.values()) for line in csv.DictReader(f)]

for i in list1:
    x=(list1[i])
    print(distancia=x[2])

To access index 3, from the tuples I copied to the list, and write to a variable?

1 answer

0

I’m not sure what you want, so please rephrase your question. But if you want to access the third index of tuples in your list of tuples, you can do so directly:

for i in range(len(list1)):
    x = list1[i][3]
    print(x)

Or in a more simplified way:

for t in list1:
    x = t[3]
    print(x)

The way you did it is wrong because in your for you are returning an entire tuple, not an index to index to list1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.