【问题标题】:Python - Group by over dictsPython - 按字典分组
【发布时间】:2017-02-24 00:30:44
【问题描述】:

我正在使用 Python 3.5,并且我有以下 dics 数组:

d1 = [{id=1, col="name", oldvalue="foo", newvalue="bar"}, {id=1, col="age", oldvalue="25", newvalue="26"}, {id=2, col="name", oldvalue="foo", newvalue="foobar"}, {id=3, col="age", oldvalue="25", newvalue="26"}]

d2 = [{id=1, col="name", oldvalue="foo", newvalue="bar"}, {id=1, col="age", oldvalue="25"]

d3 = [{id=3, col="age", oldvalue="25", newvalue="26"}]

如您所见,它显示了对特定“行”所做的一些更改。

我想知道是否有办法返回更新的总行数,所以:

def counting_updates(d):
    # ...
    return total

print counting_updates(d1) # prints 3 because 3 rows were updated
print counting_updates(d2) # prints 1 because 1 row was updated
print counting_updates(d3) # prints 1 because 1 row was updated

【问题讨论】:

  • ids 是行还是 cols?
  • 每一行都是一个字典,id为主键
  • 使用列表理解:sum(item['oldvalue'] != item['newvalue'] for item in d)

标签: python dictionary python-3.5


【解决方案1】:

如果您正在寻找唯一 ids 的数量,那么

len({row['id'] for row in d})

{} 是一个集合理解。

【讨论】:

    猜你喜欢
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2014-10-26
    相关资源
    最近更新 更多