Python 列表中字典元素(name 相等的)去重 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.orgtoc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Binb

Python 列表中字典元素(name 相等的)去重

  •  
  •   Binb Jan 27, 2018 5855 views
    This topic created in 3015 days ago, the information mentioned may be changed or developed.

    例如有如下列表: a = [ {'name':'zhangsan', 'score':20}, {'name':'lisi', 'score':25}, {'name':'zhangsan', 'score':30} ]

    想要结果: a = [ {'name': 'zhangsan', 'score':20, 'freq':2}, {'name': 'lisi', 'score': 25, 'freq':1} ]

    16 replies    2018-01-29 15:41:58 +08:00
    veelog
        1
    veelog  
       Jan 27, 2018 via iPhone   1
    reduce 把 list 专为 dict
    coolair
        2
    coolair  
       Jan 27, 2018 via Android   1
    Counter
    rookiebulls
        3
    rookiebulls  
       Jan 27, 2018 via iPhone
    用 set
    jxie0755
        4
    jxie0755  
       Jan 28, 2018   1
    用 set 会把顺序搞没了,所以最好的办法是在 set 之后,再 sorted 一次变回 list,但是 key 用原来的 index:

    print(sorted(set(a), key=a.index))
    zzth370
        5
    zzth370  
       Jan 28, 2018   1
    a = [{'name': 'zhangsan', 'score': 20}, {'name': 'lisi', 'score': 25}, {'name': 'zhangsan', 'score': 30}]
    b = [{'name': item['name']} for item in a]
    c = {item['name'] for item in a}
    d = [{'name': item['name'], 'score': item['score'], 'freq': b.count({'name': item['name']})} for item in a]
    e = []
    for item in d:
    if item['name'] in c:
    e.append(item)
    c.remove(item['name'])
    print(e)

    效果能实现,但感觉代码有点臃肿
    xpresslink
        6
    xpresslink  
       Jan 28, 2018   1
    @zzth370 确实有点,关键是用 count 会效率低的吓人。
    真心看不下去了,我又写了一个。

    #!/usr/bin/env python3.6
    # -*- coding: utf-8 -*-

    from collections import OrderedDict

    a = [ {'name':'zhangsan', 'score': 20}, {'name':'lisi', 'score':25}, {'name':'zhangsan', 'score':30} ]

    b = OrderedDict()

    for item in a:
    b.setdefault(item['name'], {**item, 'freq':0})['freq'] += 1

    print(b.values())
    # odict_values([{'name': 'zhangsan', 'score': 20, 'freq': 2}, {'name': 'lisi', 'score': 25, 'freq': 1}])
    Binb
        7
    Binb  
    OP
       Jan 28, 2018
    @xpresslink 学到了,这种 sao 操作哪里学来的?只适用于 3.5 之后版本
    thautwarm
        8
    thautwarm  
       Jan 29, 2018   2
    说实话你这需求不太对。。。

    a = [ {'name':'zhangsan', 'score':20}, {'name':'lisi', 'score':25}, {'name':'zhangsan', 'score':30} ]的结果怎么看怎么是
    [ ({'name': 'zhangsan', 'score':20}, 2), ({'name': 'lisi', 'score': 25}, 1) ] 正常。

    所以我比较偏向
    [(a[idx], count) for _, idx, count in zip(*np.unique(list(map(lambda _: _['name'], a)), return_index=True, return_counts=True))]

    当然你喜欢
    [{**a[idx], 'freq':count} for _, idx, count in zip(*np.unique(list(map(lambda _: _['name'], a)), return_index=True, return_counts=True))]
    thautwarm
        9
    thautwarm  
       Jan 29, 2018
    按照先后 index 发现的顺序
    [{**a[idx], 'freq':count} for _, idx, count in sorted(zip(*np.unique(list(map(lambda _: _['name'], a)), return_index=True, return_counts=True)), key=lambda x: x[1])]
    xpresslink
        10
    xpresslink  
       Jan 29, 2018
    @Binb 我感觉能写到我这个程度只能说是对 Python 初窥门径,很多是时候解决问题的能力并不是学来的,而是练功一样的积累出来的。推荐你精读《 Python Cook Book 3 》,《流畅的 Python 》,《 Python 标准库》这三本。
    xpresslink
        11
    xpresslink  
       Jan 29, 2018
    @Binb 只有**item 这个语法糖是 3.5 以后的,以前版本写成 dict(item, freq=0)
    IWTW
        12
    IWTW  
       Jan 29, 2018
    @xpresslink 那请问 我要让 zhangsan sorce 的值 永远保持最新的值 如何写呢
    cocoakekeyu
        13
    cocoakekeyu  
       Jan 29, 2018
    ```python
    def dedupe2(itmes, key=None):
    seen = set()
    for item in items:
    val = item if key is None else key(item)
    if val not in seen:
    yield item
    seen.add(item)
    ```

    key 换成 operator.getitem('name')
    xpresslink
        14
    xpresslink  
       Jan 29, 2018
    @IWTW 这样问题也问?直接多个 update 步骤就行了啊
    for item in a:
    temp = b.setdefault(item['name'], {**item, 'freq': 0})
    temp.update(**item)
    temp['freq'] += 1
    Binb
        15
    Binb  
    OP
       Jan 29, 2018
    @thautwarm 嗯...我也发现了
    zzth370
        16
    zzth370  
       Jan 29, 2018
    @xpresslink 感谢指点,学习了
    About     Help     Advertise     Blog     API     FAQ     Solana     2484 Online   Highest 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 42ms UTC 04:00 PVG 12:00 LAX 21:00 JFK 00:00
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86