我有两个形式的元组列表:
playerinfo = [(ansonca01,4,1871,1,RC1),(forceda01,44,1871,1,WS3),(mathebo01,68,1871,1,FW1)]
idmatch = [(ansonca01,Anson,Cap,05/06/1871),(aaroh101,Aaron,Hank,04/13/1954),(aarot101,Aaron,Tommie,04/10/1962)]
我想知道的是,如何迭代这两个列表,以及来自" playerinfo"的元组中的第一个元素。匹配来自" idmatch"的元组中的第一个元素,将匹配的元组合并在一起以产生新的元组列表?形式如下:
merged_data = [(ansonca01,4,1871,1,RC1, Anson,Cap,05/06/1871),(...),(...), etc.]
新元组列表的ID号与正确播放器的名字和姓氏相匹配。
背景信息:我试图合并棒球统计数据的两个CSV文档,但是具有所有相关统计数据的文档并不包含玩家名称,只有参考数字,例如' ansoc101',而第二个文档包含一列中的引用号以及另一列中相应播放器的名和姓。
CSV的大小太大,无法手动执行此操作(约20,000名玩家),因此我尝试自动完成此过程。
答案 0 :(得分:3)
使用列表推导来迭代列表:
[x + y[1:] for x in list1 for y in list2 if x[0] == y[0]]
我在列表上尝试了这个:
list1 = [("this", 1, 2, 3), ("that", 1, 2, 3), ("other", 1, 2, 3)]
list2 = [("this", 5, 6, 7), ("that", 10, 11, 12), ("notother", 1, 2, 3)]
得到了:
[('this', 1, 2, 3, 5, 6, 7), ('that', 1, 2, 3, 10, 11, 12)]
这就是你想要的吗?
答案 1 :(得分:2)
您可以先创建一个字典以启用快速ID号查找,然后使用列表解析非常有效地将两个列表中的数据合并在一起:
import operator
playerinfo = [('ansonca01', 4, 1871, 1, 'RC1'),
('forceda01', 44, 1871, 1, 'WS3'),
('mathebo01', 68, 1871, 1, 'FW1')]
idmatch = [('ansonca01', 'Anson', 'Cap', '05/06/1871'),
('aaroh101', 'Aaron', 'Hank', '04/13/1954'),
('aarot101', 'Aaron', 'Tommie', '04/10/1962')]
id = operator.itemgetter(0) # To get id field.
idinfo = {id(rec): rec[1:] for rec in idmatch} # Dict for fast look-ups.
merged = [info + idinfo[id(info)] for info in playerinfo if id(info) in idinfo]
print(merged) # -> [('ansonca01', 4, 1871, 1, 'RC1', 'Anson', 'Cap', '05/06/1871')]
答案 2 :(得分:0)
<强>词典强>
playerinfo
列表并创建字典,其中key是元组中的第一个项目,value是所有项目的列表。idmatch
列表并检查结果字典中的第一个元组项目。如果它存在,则通过list extend方法使用新值扩展key的值。演示:
import pprint
playerinfo = [("ansonca01",4,1871,1,"RC1"),\
("forceda01",44,1871,1,"WS3"),\
("mathebo01",68,1871,1,"FW1")]
idmatch = [("ansonca01","Anson","Cap","05/06/1871"),\
("aaroh101","Aaron","Hank","04/13/1954"),\
("aarot101","Aaron","Tommie","04/10/1962")]
result = {}
for i in playerinfo:
result[i[0]] = list(i[:])
print "Debug Rsult1:"
pprint.pprint(result)
for i in idmatch:
if i[0] in result:
result[i[0]].extend(list(i[1:]))
print "\nDebug Rsult2:"
pprint.pprint(result)
final_rs = []
for i,j in result.items():
final_rs.append(tuple(j))
print "\nFinal result:"
pprint.pprint(final_rs)
输出:
infogrid@infogrid-vivek:~/workspace/vtestproject$ python task4.py
Debug Rsult1:
{'ansonca01': ['ansonca01', 4, 1871, 1, 'RC1'],
'forceda01': ['forceda01', 44, 1871, 1, 'WS3'],
'mathebo01': ['mathebo01', 68, 1871, 1, 'FW1']}
Debug Rsult2:
{'ansonca01': ['ansonca01', 4, 1871, 1, 'RC1', 'Anson', 'Cap', '05/06/1871'],
'forceda01': ['forceda01', 44, 1871, 1, 'WS3'],
'mathebo01': ['mathebo01', 68, 1871, 1, 'FW1']}
Final result:
[('ansonca01', 4, 1871, 1, 'RC1', 'Anson', 'Cap', '05/06/1871'),
('forceda01', 44, 1871, 1, 'WS3'),
('mathebo01', 68, 1871, 1, 'FW1')]
infogrid@infogrid-vivek:~/workspace/vtestproject$