打印具有相同列的行

Print rows which have same column

我还是个新手,一直卡在这种情况下。

我有一个类似于以下内容的 csv 文件。

import csv

csvpath = "C:/Test/test.csv"

with open(csvpath) as f:
    csv = csv.DictReader(f)
    for row in csv:
        print(row)

输出为:

{'NAME': 'John', 'NICKNAME': 'Big John', 'COUNTRY': 'Canada', 'CITY': 'Toronto'}
{'NAME': 'David', 'NICKNAME': 'Small Jogn', 'COUNTRY': 'Canada', 'CITY': 'Toronto'}
{'NAME': 'Alan', 'NICKNAME': 'The Bull', 'COUNTRY': 'England', 'CITY': 'London'}
{'NAME': 'Ethan', 'NICKNAME': 'The Hawk', 'COUNTRY': 'England', 'CITY': 'London'}
{'NAME': 'Ivan', 'NICKNAME': 'The Russian', 'COUNTRY': 'Russia', 'CITY': 'Moscow'}
{'NAME': 'Boris', 'NICKNAME': 'The Bear', 'COUNTRY': 'Russia', 'CITY': 'Moscow'}

是否可以先只打印国家/地区为加拿大的行。然后我想要另一个循环来打印包含英格兰国家和俄罗斯国家的行。然而,国家会一直被编辑,所以它不会相同,并且这个列表中每天可能有不同的国家和国家数量。所以基本上我需要在不同的 for 循环中分别打印具有相同国家/地区的行。

当它们都在一个数组中时。

def print_countries(array,countryname):
 print("results for: ", countryname)
 for item in array:
   if item['COUNTRY'] == countryname:
      print(item)

让它成为一个函数。如果您想在 CSV 文件中打印每个国家/地区,我会用每个名称构建一个数组。

def get_countrynames(array):
 countryname_list = []
 for row in array:
  if row['COUNTRY'] not in countryname_list:
    countryname_list.append(row['COUNTRY'])
 return countryname_list

with open(csvpath) as f:
    csv = csv.DictReader(f)
    names = get_countrynames(csv)
    for country in names:
     print_countries(csv,country)

希望这有效,我自己没有测试

下面的代码按国家/地区对数据进行分组:(基于问题中的数据结构)

from collections import defaultdict

data = [{'NAME': 'John', 'NICKNAME': 'Big John', 'COUNTRY': 'Canada', 'CITY': 'Toronto'},
        {'NAME': 'David', 'NICKNAME': 'Small Jogn', 'COUNTRY': 'Canada', 'CITY': 'Toronto'},
        {'NAME': 'Alan', 'NICKNAME': 'The Bull', 'COUNTRY': 'England', 'CITY': 'London'},
        {'NAME': 'Ethan', 'NICKNAME': 'The Hawk', 'COUNTRY': 'England', 'CITY': 'London'},
        {'NAME': 'Ivan', 'NICKNAME': 'The Russian', 'COUNTRY': 'Russia', 'CITY': 'Moscow'},
        {'NAME': 'Boris', 'NICKNAME': 'The Bear', 'COUNTRY': 'Russia', 'CITY': 'Moscow'}]

data_by_country = defaultdict(list)
for entry in data:
    data_by_country[entry['COUNTRY']].append(entry)

for country, info_lst in data_by_country.items():
    print(country)
    for info in info_lst:
        print(f'\t {info}')

输出

Canada
     {'NAME': 'John', 'NICKNAME': 'Big John', 'COUNTRY': 'Canada', 'CITY': 'Toronto'}
     {'NAME': 'David', 'NICKNAME': 'Small Jogn', 'COUNTRY': 'Canada', 'CITY': 'Toronto'}
England
     {'NAME': 'Alan', 'NICKNAME': 'The Bull', 'COUNTRY': 'England', 'CITY': 'London'}
     {'NAME': 'Ethan', 'NICKNAME': 'The Hawk', 'COUNTRY': 'England', 'CITY': 'London'}
Russia
     {'NAME': 'Ivan', 'NICKNAME': 'The Russian', 'COUNTRY': 'Russia', 'CITY': 'Moscow'}
     {'NAME': 'Boris', 'NICKNAME': 'The Bear', 'COUNTRY': 'Russia', 'CITY': 'Moscow'}

根据某些标准从集合中选择项目称为过滤

Python 提供 filter built-in function to do this, or you can use a list comprehension or a generator 表达式来实现相同的结果。

列表理解比 filter 更快,并且被认为更“pythonic”,但我发现 filter 有时会使代码更容易理解。生成器表达式在语法上类似于列表理解,但使用更少的内存(并且只能循环一次)。

下面的函数显示了如何使用所有三个选项。它接受一个打开的文件和一个国家名称列表(作为字符串)作为其参数,并打印出为每个国家找到的行。

import csv

def print_rows(file, countries):
    reader = csv.DictReader(file)
    # Make a list of all the rows so we can loop over them more than once.
    rows = list(reader)
    for country in countries:
        print('Printing rows for', country)

        # Filter the rows by country.
        # Using the filter built-in function.
        filtered_rows = filter(lambda row: row['COUNTRY'] == country, rows)
        # List comprehension.
        # filtered_rows = [row for row in rows if row['COUNTRY'] == country]
        # Generator expression.
        # filtered_rows = (row for row in rows if row['COUNTRY'] == country)
        for row in filtered_rows:
            print(row)
        print()
    return


countries = ['Canada', 'Russia']

csvpath = "C:/Test/test.csv"

with open(csvpath) as f:
    csv = csv.DictReader(f)

    print_rows(f, countries)

输出:

Printing rows for Canada
{'NAME': 'John', 'NICKNAME': 'Big John', 'COUNTRY': 'Canada', 'CITY': 'Toronto'}
{'NAME': 'David', 'NICKNAME': 'Small Jogn', 'COUNTRY': 'Canada', 'CITY': 'Toronto'}

Printing rows for Russia
{'NAME': 'Ivan', 'NICKNAME': 'The Russian', 'COUNTRY': 'Russia', 'CITY': 'Moscow'}
{'NAME': 'Boris', 'NICKNAME': 'The Bear', 'COUNTRY': 'Russia', 'CITY': 'Moscow'}