Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
比较python中的csv文件以查看两者中的内容_Python_Csv_Comparison - Fatal编程技术网

比较python中的csv文件以查看两者中的内容

比较python中的csv文件以查看两者中的内容,python,csv,comparison,Python,Csv,Comparison,我有两个csv文件,我想比较其中一个是所有国家的主文件,另一个只有几个国家。这是我为一些基本测试所做的尝试: char = {} with open('all.csv', 'rb') as lookupfile: for number, line in enumerate(lookupfile): chars[line.strip()] = number with open('locations.csv') as textfile: text = textfil

我有两个csv文件,我想比较其中一个是所有国家的主文件,另一个只有几个国家。这是我为一些基本测试所做的尝试:

char = {}
with open('all.csv', 'rb') as lookupfile:
    for number, line in enumerate(lookupfile):
        chars[line.strip()] = number

with open('locations.csv') as textfile:
    text = textfile.read()
    print text
for char in text:
    if char in chars:
        print("Country found {0} found in row {1}".format(char, chars[char]))
我正试图获得国家主文件的最终输出,其中有一个第二列,指示它是否出现在其他列表中


谢谢

您可以使用与原始循环完全相同的逻辑:

with open('locations.csv') as textfile:
    for line in textfile:
        if char.strip() in chars:
            print("Country found {0} found in row {1}".format(char, chars[char]))
试试这个:

编写一个函数,将CSV转换为Python字典,其中包含在CSV中找到的每个国家/地区的关键字。它可以是这样的: {'US':正确,'UK':正确}

对两个CSV文件执行此操作。 现在,对要比较的csv的dictionary.keys进行迭代,只需检查另一个dictionary是否具有相同的键。 这将是一个非常快速的算法,因为字典为我们提供了固定时间的查找,并且您有一个数据结构,您可以轻松使用它查看您找到的国家

正如Eric在评论中提到的,您也可以使用来处理此问题。这实际上可能是更简单、更好的方法:

set1 = set()                   # A new empty set
set1.add("country")
if country in set:
  #do something

我对python相当陌生,所以我必须为csv文件中的所有内容制作一个键,就像您显示为变量一样吗?如果您只是比较国家,那么您只需要为这些国家制作键。dict[国家]=正确@Ericleveil集合的问题是查找有一个最坏的情况。@Calvinfoedge集合和字典在同一条船上…@Ericleveil啊,你说得对,我以为字典查找总是O1