質問

So for my program I have two definitions, get_codes and get_data, that I created 8 total lists from, shown below:

CountryCodes=open("CountryCodes.csv",'r')
CountryData=open("CountryData.csv", 'r')

def get_codes(file):
    country_code=[]
    country_name=[]
    continent=[]

    for line in CountryCodes: 
        c_fields=line.split(",")

        c_field1=c_fields[0].strip()
        c_field2=c_fields[1].strip()
        c_field3=c_fields[2].strip() 

        country_code.append(c_field1)
        country_name.append(c_field2)
        continent.append(c_field3)

    return country_code, country_name, continent

def get_data(file): 
    data_country_code=[]
    country_pop=[]
    country_area=[]
    country_gdp=[]
    country_lit_rate=[]

    for line in CountryData: 
        d_fields=line.split(",")

        d_field1=d_fields[0].strip()
        d_field2=d_fields[1].strip()
        d_field3=d_fields[2].strip()
        d_field4=d_fields[3].strip()
        d_field5=d_fields[4].strip()

        data_country_code.append(d_field1)
        country_pop.append(int(d_field2))
        country_area.append(d_field3)
        country_gdp.append(int(d_field4))
        country_lit_rate.append(d_field5)

    return data_country_code, country_pop, country_area, country_gdp, country_lit_rate

Now what I have to do is create a menu option (I have the menu) that gives the country_pop in ascending, and later descending, order. Here's what I have so far:

def asc_sort():
    for x in range (0,len(country_pop)):
        country_pop2=sorted(country_pop)

I have the sorting down, but my professor doesn't only want the country_pop2 printed. She also wants the country_name, which is in CountryCodes, not CountryData where the population is. So the country_pop's index, x, should also be x in data_country_code. I then need to take the input of x in data_country_code, let's say it's AL, and find that in country_code. Next I'll have to find the corresponding country_name, Albania, to the country_code, AL and list the country_name with the country_pop which I assume would be something like:

print("%-10s \t %-10s \t" %("NAMES","POPULATION"))
for ind in range (0,len(list1)):
    if ind%10==9:
        input("Press ENTER to continue")
    print("%-2s \t %-10s \t %-10s \t %-10s \t %-10s \t" %(I'd need help here)

(I need the %-10s part for formatting and the if statement because my list is so long I only want a few to show at a time) Any help would be appreciated, and if anyone needs more explaining I'll do my best!

役に立ちましたか?

解決

I think the following code does what you want:

with open("CountryCodes.csv",'r') as CountryCodes:
    genc = (line.split(',') for line in CountryCodes)

    c2n = dict((c_fields[0].strip(),c_fields[1].strip())
               for c_fields in genc)

with open("CountryData.csv",'r') as CountryData:
    gend = (line.split(',') for line in CountryData)

    the_data = [ (c2n[d_fields[0].strip()], # data_country_code
                  int(d_fields[1]),         # country_pop
                  d_fields[2].strip(),      # country_area
                  d_fields[3].strip(),      # country_gdp
                  d_fields[4].strip())      # country_lit_rate
                 for d_fields in gend ]

the_data.sort(key = lambda x: x[1])

p = 10
for i in xrange(0,len(the_data),p):
    if i:  raw_input("  Press ENTER to continue\n")
    print ('\n'.join("%-10s \t %-10s \t %-10s \t %-10s \t %s"
                     % el for el in the_data[i:i+p]) )

The dictionary c2n gives the names corresponding to codes.

The population field is certainly a string expressing an integer that doesn't need to be striped, even if there are whitespaces in it (blanks, tabs... not newlines)

.

EDIT

If you're not authorized to use a dictionary but only lists, you cab do like that:

with open("CountryCodes.csv",'r') as CountryCodes:
    genc = (line.split(',') for line in CountryCodes)
    lic = [map(str.strip,row) for row in genc]

def name_of(x,lic=lic):
  for code,name,continent in lic:
    if x==code:
      return name

with open("CountryData.csv",'r') as CountryData:
    gend = (line.split(',') for line in CountryData)

    the_data = [ (name_of(d_fields[0].strip()), # data_country_code
                  int(d_fields[1]),         # country_pop
                  d_fields[2].strip(),      # country_area
                  d_fields[3].strip(),      # country_gdp
                  d_fields[4].strip())      # country_lit_rate
                 for d_fields in gend ]

他のヒント

you need to do two things:

  1. store all the data in a line from CountryData in a tuple, rather than separate lists. that way, when you rearrange everything in your sort, you also rearrange the county codes.

  2. store the data from CountryCodes in a dict, so that you can go from code to country name.

i'm not sure i should be doing all your homework for you, but if you have data like this:

country_data = [('uk', 123), ('usa', 42), ('cl', 99)]
country_names = {'uk': 'united kingdom', 'usa': 'united states', 'cl': 'chile'}

then this would give you the country names ordered by the numbers:

sorted_data = sorted(country_data, key=lambda data: data[1])
for (code, value) in sorted_data:
    print(country_names[code], value)

note how the key picks out the second element of the tuple to sort. so, for ('uk', 123) it will give 123, which is what you want to sort by.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top