python - 将文本文件中的一组值与另一组值进行匹配

标签 python list python-3.x

我有一个包含以下信息的文本文件:

1961 - Roger (Male)
1962 - Roger (Male)
1963 - Roger (Male)
1963 - Jessica (Female)
1964 - Jessica (Female)
1965 - Jessica (Female)
1966 - Jessica (Female)

如果我想在文件中搜索单词“Roger”,我希望它打印出该名称的相应年份,即 1961、1962、1963。解决此问题的最佳方法是什么?

我是用字典来做的,但后来意识到字典不能有重复的值,并且文本文件中两次提到 1963,所以它不起作用。

我正在使用 Python 3,谢谢。

最佳答案

使用以名称为键的字典,并将年份存储在列表中:

In [1]: with open("data1.txt") as f:
   ...:     dic={}
   ...:     for line in f:
   ...:         spl=line.split()
   ...:         dic.setdefault(spl[2],[]).append(int(spl[0]))
   ...:     for name in dic :    
   ...:         print (name,dic[name])
   ...:       

Roger [1961, 1962, 1963]
Jessica [1963, 1964, 1965, 1966]

或者您也可以使用collections.defaultdict :

In [2]: from collections import defaultdict

In [3]: with open("data1.txt") as f:
   ...:     dic=defaultdict(list)
   ...:     for line in f:
   ...:         
   ...:         spl=line.split()
   ...:         dic[spl[2]].append(int(spl[0]))
   ...:     for name in dic:    
   ...:         print name,dic[name]
   ...:         
Roger [1961, 1962, 1963]
Jessica [1963, 1964, 1965, 1966]

关于python - 将文本文件中的一组值与另一组值进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13427589/

相关文章:

python - pandas timeseries DF 切片和选择

python - 检查列表或字符串以查看是否存在来自另一个列表的字符串

algorithm - 有人可以解释这个 RSA 示例的最后部分发生了什么吗?

python - 使用线程和/或多处理同时移动多个 turtle

python - 在两列上分组并使用 pandas - Python 在特定列上应用转换(分区)、滚动和连接

python - 使用 Chrome 时的 Selenium "selenium.common.exceptions.NoSuchElementException"

c# - 从列表中删除特定元素

python-3.x - 将一列替换为另一列,除非 Pandas 中另一列为 NaN

python | 26个名为a-z的列表,每个字母都是字符串,随机选择字母,如何选择列表

python - 使用不同数量的变量进行查询