Joe
Joe

Reputation: 512

Return a list of items from a text file to be indexed

I am trying to write a function that returns a list of cities from a text file so that when the function is called, you can put an index after it, and it will return the corresponding city.

Example:

citylist('MYFILE.txt')[3]

So far, I have

def citylist(filename):
    assert type(filename)==str

    with open(filename) as FileObject:
        for line in FileObject:
            q=line.split('\t')
            print q[12],

There are 500 complaints. After I split each string (complaint) into a list, the city name is the 13th index in the list. But I am stuck as all I can get it to do is print all of the city names as non data types that cannot be indexed.

Upvotes: 1

Views: 118

Answers (2)

mgilson
mgilson

Reputation: 309929

You could create a list and return it:

def citylist(filename):
  assert type(filename)==str  #isinstance(filename,str) is more idiomatic here.

  output = []
  with open(filename) as FileObject:
    for line in FileObject:
      q = line.split('\t')
      output.append(q[12]) 
  return output

Alternatively, and more succinctly:

def citylist(filename):
    with open(filename) as f:
        return [ line.split('\t')[12] for line in f ]

where I've built the list using a list-comprehension in this last example.

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208475

def citylist(filename):
  assert isinstance(filename, str)
  return [line.split('\t')[12] for line in open(filename)]

The list comprehension is equivalent to the following expanded for loop:

result = []
for line in open(filename):
  result.append(line.split('\t')[12]) 

Upvotes: 0

Related Questions