以下循环通过两个列表(源和主)扫描匹配的 ID(索引 0),然后对于 ID 匹配的那一行,它通过更改的列查找并打印它们:
for row in source:
identifier = row[0]
new_cols = row[1:]
for row in master:
old_cols = row[1:]
if identifier == row[0]:
print(row[0]) # ID that matched
changed_cols = [col for col in new_cols if col not in old_cols]
print(changed_cols) # cols that differ
列表每行包含超过 20 列,所以我认为使用 row[1:] 会很聪明,但我不确定如何使用此方法来获取更改后的列的索引。感谢您的帮助。
更新:
source = [['1002', '', '', '', '13RA11', '', 'LO', '4302', '99111', '0', ''],
['1076', '', '', '', '13RA11', '', 'LO', '4302', '999111', '0', ''],
['1130', '', '', '', '11HOT1A', '', 'LO', '4302', '99111', '0', '']]
master = [['1002', '', '', '', '13RA11', '', 'LO', '4302', '99111', '0', ''],
['1076', '', '', '', '13RA11', '', 'LO', '4302', '999111', '1', ''],
['1130', '', '', '', '13RA11', '', 'LO', '4302', '99111', '1', '']]
最佳答案
您是否考虑过使用enumerate
?你的列表理解会变成这样:
changed_cols = [(ID,col) for ID,col in enumerate(new_cols) if col not in old_cols]
这对我来说似乎是最简单的解决方案。
如果我误解了您的问题,请告诉我,我会努力调整我的解决方案:)
编辑:我想你可能想要像加里建议的那样的东西:
changed_cols = [(ID,col) for ID,col in enumerate(new_cols) if col != old_cols[ID]]
这将只比较每个新列对应的旧列。我猜想这是您真正想要的功能。如果您不确定其中的区别,请告诉我:)
关于python - 打印出列表每行更改列的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31855625/