python - 打印出列表每行更改列的索引

标签 python list

以下循环通过两个列表(源和主)扫描匹配的 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/

相关文章:

c# - 从 List<string> 中选择匹配的行

python - For 循环的迭代次数比我在 Python 中预期的要少

python - datetime.combine() 和 pytz.localize() 之间的区别

python - 与 C 等效程序相比,解压例程非常慢?

python - boto3.Bucket.upload_file 是阻塞还是非阻塞?

python - 双循环比较列表有什么Python提示或技巧吗?

javascript - 如何获取json对象标题

c# - 将一个非常 Python 风格的库移植到 .NET

Python正则表达式排序问题

python - 如何旋转 Python 列表以将特定值居中