比较python

时间:2015-11-16 17:25:44

标签: python python-2.7

我需要比较我组织的两个国家/地区列表,一个按人口划分,一个按地区划分,以便打印出两个列在同一位置的国家/地区。到目前为止,我所尝试的任何事情都导致它只返回一个在两个列表中具有相同位置的国家,而应该总共有6个。

def coincidingCountries():
countries = readCountries()
for i in range(0,len(countries)): 
        swap = False
        for j in range(0,len(countries)-(i+1)): 
            if countries[j][1]>countries[j+1][1]:
                temp = countries[j+1] 
                countries[j+1] = countries[j] 
                countries[j] = temp
                swap = True 

for i in range(0,len(countries)):   
        smallest = i
        for j in range(i,len(countries)):
            if countries[j][2]< countries[smallest][2]:
                smallest = j

        temp = countries[i]
        countries[i] = countries[smallest]
        countries[smallest] = temp

2 个答案:

答案 0 :(得分:2)

尝试pandas

import pandas as pd

pop = ['a', 'b', 'c', 'd', 'e', 'i']
area = ['a', 'c', 'b', 'd', 'e', 'f']

countries = pd.DataFrame(data = {'pop': pop, 'area': area})
print countries[countries['area']==countries['pop']]

    area    pop
0   a   a
3   d   d
4   e   e

这假设您的两个列表已经排序,并将打印值匹配的表的行。

答案 1 :(得分:1)

确实,使用python的功能 zip(a,b)为0和len(a)之间的i创建元组列表(a_i,b_i),前提是两个数组的大小相同。

sorted(a,key)对数组w.r.t键进行排序,如下所示:

zip(sorted(countries, key=lambda country: country[1]), sorted(countries, key=lambda country: country[2])

应该做的伎俩

作为评论者添加,您可能想要了解列表推导。 http://www.secnetix.de/olli/Python/list_comprehensions.hawk

至于zip和已排序,请查看官方文档: https://docs.python.org/3.3/library/functions.html