【问题标题】:How to append everything under a list index to current?如何将列表索引下的所有内容附加到当前?
【发布时间】:2017-12-02 15:34:37
【问题描述】:

不知道这会叫什么,但我有类似的东西:

dict = {
    1: "{} test string 01",
    2: "{} test string 02",
    3: "{} test string 03
}

如果我想遍历每一个并将它们连接起来,使3: 包含{} test string 03 {} test string 02 test string01 并且2: 包含{} test string 02 {} test string 01,我该怎么做呢?

如果 dict 只有几个条目,那会很容易,但如果 dict 包含 20 多个项目,那么最有效的方法是什么……向后递归(不确定这是否是正确的术语) ?

【问题讨论】:

  • 很遗憾,这不是论坛或教程服务。请花时间阅读How to Ask 和该页面上的其他链接。您应该花一些时间通过the Tutorial 练习这些示例。它将向您介绍 Python 必须提供的工具,您甚至可能会开始获得解决问题的想法。
  • 字典的内容是无序的,所以输出会有点随机,除非它被排序(在这种情况下是按键值)。

标签: python


【解决方案1】:

您可以将itertools.accumulate 用于 Python3:

import itertools
import operator
import re
dict = {
1: "{} test string 01",
2: "{} test string 02",
3: "{} test string 03"
}
new_dict = {a:' '.join(re.split('(?<=\d\{\})\s(?=test)', b)[::-1]) for a, b in zip(sorted(dict.keys()), sorted(itertools.accumulate(sorted(dict.values(), key=lambda x:int(x[-1])), func=operator.add)))}

输出:

{1: '{} test string 01', 2: 'test string 02 {} test string 01{}', 3: 'test string 03 test string 02{} {} test string 01{}'}

【讨论】:

    【解决方案2】:

    你可以试试这个:

    d = {
        1: "{} test string 01",
        2: "{} test string 02",
        3: "{} test string 03"
    }
    
    values = list(d.values())
    keys = list(d.keys())
    
    d = dict((i , ' '.join(val for val in reversed(values[:i]))) for i in keys)
    print(d)
    

    输出:

    {1: '{} test string 01', 2: '{} test string 02 {} test string 01', 3: '{} test string 03 {} test string 02 {} test string 01'}
    

    【讨论】:

      猜你喜欢
      • 2016-08-15
      • 1970-01-01
      • 2012-06-04
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 2018-02-08
      相关资源
      最近更新 更多