hiboshi
V2EX  ›  问与答

Python 如何实现这样的数据结构

  •  
  •   hiboshi · Aug 22, 2017 · 1944 views
    This topic created in 3213 days ago, the information mentioned may be changed or developed.

    初学 py,貌似 不支持 php 这样 dict+=字符 的写法。

    $aa = array(
    
        array('id'=>1,'txt'=>"aaa"),
        array('id'=>1,'txt'=>"bbb"),
        array('id'=>1,'txt'=>"ccc"),
        array('id'=>2,'txt'=>"ddd"),
        array('id'=>2,'txt'=>"eee"),
        array('id'=>3,'txt'=>"fff"),
    );
    
    foreach ( $aa as $k=>$v) {
        $tmp[$v['id']] .= $v['txt'].'|';
    }
    print_r($tmp);
    exit();
    
    5 replies    2017-08-22 20:43:51 +08:00
    ryd994
        1
    ryd994  
       Aug 22, 2017 via Android
    .append
    kkhaike
        2
    kkhaike  
       Aug 22, 2017
    aa = [
    {'id': 1,'txt': "aaa"},
    {'id': 1,'txt': "bbb"},
    {'id': 1,'txt': "ccc"},
    {'id': 2,'txt': "ddd"},
    {'id': 2,'txt': "eee"},
    {'id': 3,'txt': "fff"},
    ]

    tmp = {}
    for v in aa:
    tmp[v['id']] = ((v['id'] in tmp) and tmp[v['id']] or '') + v['txt'] + '|'
    print tmp

    有很多写法,这个这是比较类似你的代码
    hiboshi
        3
    hiboshi  
    OP
       Aug 22, 2017
    @kkhaike 学到了。其实 也是支持 += 的,只是没用对,你说的 其他方式 是哪些的,正常点实现,比如 python 是不是有什么 语法 能直接实现 这种功能?不需要按照上面的 php 思维方式
    petelin
        4
    petelin  
       Aug 22, 2017
    In [22]: for item in aa:
    ...: tmp[item['id']]= tmp.get(item['id'], '') + item['txt'] + '|'
    petelin
        5
    petelin  
       Aug 22, 2017   ❤️ 1
    In [73]: for k,g in groupby(aa, lambda x:x['id']):
    ...: tmp[k] = '|'.join([item['txt'] for item in list(g)]) + '|'
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3315 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 62ms · UTC 00:32 · PVG 08:32 · LAX 17:32 · JFK 20:32
    ♥ Do have faith in what you're doing.