How could I create a tuple with for-loops to create a list variable using a file with headers and its corresponding data

Viewed 48

So I have a text file containing 22 lines and three headers which is:

  1. economy name
  2. unique economy code given the World Bank standard (3 uppercase letters)
  3. Trade-to-GDP from year 1990 to year 2019 (30 years, 30 data points); 0.3216 means that trade-to-gdp ratio for Australia in 1990 is 32.16%

The code I have used to import this file and open/read it is:

def Input(filename):        
    f = open(filename, 'r')      
    lines = f.readlines()        
    lines = [l.strip() for l in lines]   
    f.close()
    return lines

However once I have done that I have to create a code with for-loops to create a list variable named result. It should contain 22 tuples, and each tuple contains four elements:

  1. economy name,
  2. World Bank economy code,
  3. average trade-to-gdp ratio for this economy from 1990 to 2004,
  4. average trade-to-gdp ratio for this economy from 2005 to 2019.

Coming out like

('Australia', 'AUS', '0.378', '0.423')

So far the code I have written looks like this:

 def result:
   name, age, height, weight = zip(*[l.split() for l in text_file.readlines()])

I am having trouble starting this and knowing how to grapple with the multiple years required and output all the countries with corresponding ratios.Here is the table of all the data I have on the text file.

enter image description here

1 Answers

I would suggest to use Pandas for this. You can simply do:

import pandas as pd
df = read_csv('filename.csv')
for index, row in df.iterrows():
    ***Do something***

In for loop you can use row['columnName'] and get the data, For example: row['code'] or row['1999'].

This approach will be lot easier for you to carry operations and process the data.

Also to answer your approach:

You can iter over the lines and extract the data using index.

Try the below code:

def Input(filename):        
    f = open(filename, 'r')      
    lines = f.readlines()        
    lines = [l.strip().split() for l in lines]   
    f.close()
    return lines

for line in lines[1:]:
    total = sum([float(x) for x in line[2:17])# this will give you sum of values from 1990 to 2004
    total2 = sum([float(x) for x in line[17:])# this will give you sum of values from 2005 to 2019
    val= (line[0], line[1], total, total1) #This will give you tuple 

You can continue the approach and create a tuple in each for loop.

Related