V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
hiboshi
V2EX  ›  问与答

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

  •  
  •   hiboshi · 2017-08-22 16:28:22 +08:00 · 1470 次点击
    这是一个创建于 2437 天前的主题,其中的信息可能已经有所发展或是发生改变。

    初学 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 条回复    2017-08-22 20:43:51 +08:00
    ryd994
        1
    ryd994  
       2017-08-22 16:46:04 +08:00 via Android
    .append
    kkhaike
        2
    kkhaike  
       2017-08-22 16:48:03 +08:00
    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
       2017-08-22 17:13:27 +08:00
    @kkhaike 学到了。其实 也是支持 += 的,只是没用对,你说的 其他方式 是哪些的,正常点实现,比如 python 是不是有什么 语法 能直接实现 这种功能?不需要按照上面的 php 思维方式
    petelin
        4
    petelin  
       2017-08-22 20:29:26 +08:00
    In [22]: for item in aa:
    ...: tmp[item['id']]= tmp.get(item['id'], '') + item['txt'] + '|'
    petelin
        5
    petelin  
       2017-08-22 20:43:51 +08:00   ❤️ 1
    In [73]: for k,g in groupby(aa, lambda x:x['id']):
    ...: tmp[k] = '|'.join([item['txt'] for item in list(g)]) + '|'
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4249 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 04:09 · PVG 12:09 · LAX 21:09 · JFK 00:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.