在python中比较两个列表,并将结果保存在一个单独的列表中。

问题描述 投票:0回答:1

我的代码到目前为止。

import csv

myIds = ['1234','3456','76']
countries = []

# open the file
with open('my.csv', 'r') as infile:
  # read the file as a dictionary for each row ({header : value})
  reader = csv.DictReader(infile)
  data = {}
  for row in reader:
    for header, value in row.items():
      try:
        data[header].append(value)
      except KeyError:
        data[header] = [value]

# extract the variables and assign to lists
myFileIds = data['id']
myFileCountry = data['country']
listfromfile = [a + " " + b for a, b in zip(myFileIds, myFileCountry)]

上面的代码在listfromfile中给出了如下结果。

listfromfile = ['1 Uruguay', '2 Vatican', '1234 US', '3456 UK', '5678 Brazil','10111 Argentina','234567 Spain']

我的目标是列出一个在my.csv文件中出现过ID的国家,但也有可能myIds列表中的ID在my.csv文件中不存在。那么我需要在列表中那个地方显示值为'不支持的国家'。两个列表中的myIds和国家的长度应该是一样的,这样我就可以知道我列表中的第一个id对应于另一个列表中的第一个国家等等。希望的结果。

myIds = ['1234','3456','76']
countries = ['US', 'UK', 'Unsupported Country']

或者,我正在尝试用pandas,但也不成功:(

import pandas as pd

df=pd.read_csv('my.csv')
myIds = ['1234','3456','76']

countries = df.loc[df["id"].isin(myIds),"country"].tolist()

my.csv。

id     country
1      Uruguay
2      Vatican
1234   US
3456   UK
5678   Brazil
10111  Argentina
234567 Spain

谁能帮我解决这个问题?

python python-3.x list csv
1个回答
1
投票

你可以使用数据帧来实现这个功能。

import pandas as pd
input_df = pd.read_csv("test.csv")
myIds = ['1234','3456','76']
my_ids_df = pd.DataFrame(myIds,columns=['id']).astype(int)
output_df = pd.merge(input_df, my_ids_df, on=['id'], how='right')
output_df['country'] = output_df['country'].fillna('Unsupported Country')
print(list(zip(output_df['id'].values.tolist(),output_df['country'].values.tolist())))

1
投票

也许这对你的目的是有用的。

假设你的文件数据和你的例子中的一样. 否则,你可以用另一个字符来分割。

>>> from collections import defaultdict
>>> country_data = defaultdict(lambda: 'Unsupported Country')
>>> 
>>> for line in open("my.csv", 'r'):
...     try:
...         id, country = line.split()
...         country_data[int(id)] = country
...         country_data[country] = int(id)
...     except ValueError:
...         pass # Row isn't in the right format. Skip it.
...         
>>> country_data['Vatican']
2
>>> country_data[2]
'Vatican'
>>> country_data['Moojoophorbovia']
'Unsupported Country'
>>> 

如果你不是想把一个方形的钉子装进一个圆形的洞里,假设你需要两个你必须保持同步的列表--然后试图把你的文件数据装进它们里面,上面的方法可能会解决读取国家数据的问题,并通过ID索引来访问它,或者从国家名称中获取ID。


0
投票
 import pandas as pd

 myIds = ['1234','3456','76']

 df = pd.DataFrame(myIds, columns=['id'])

 fields=['id', 'country']

 df = df1
 df2 = pd.read_csv('my.csv', sep = ',', usecols=fields)
 df3 = df1.merge(df2, on="id", how='left')
 df3['country'].fillna('Unsupported Country', inplace=True)
 del df3['id']
 countries = df3['country'].tolist()

上面的方法对我来说是可行的。然而,仍然试图找到一个更简单的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.