【问题标题】:How to apply a function to a sequence of dicts?如何将函数应用于一系列字典?
【发布时间】:2019-04-30 12:56:40
【问题描述】:

我有以下功能:

def count_chars(e):
    return len(e)

我正在迭代一个json如下:

在:

a_lis = []
with open('../JSON_FILE.json','r') as fa:
    a = json.load(fa)
    for e in a['entries']:
        pprint(e)

输出:

{'data': ['string'], 'type': 'one'}
{'data': ['a string '], 'type': 'one'}
{'data': ['another string'], 'type': 'three'}
...
{'data': ['one more string'], 'type': 'two'}

如何应用count_chars 函数并将其添加或更新为'data' 列表中的新字符串?例如,预期的输出如下所示:

{'data': ['string','6'], 'type': 'one'}
{'data': ['a string','8'], 'type': 'one'}
{'data': ['another string','14'], 'type': 'three'}
...
{'data': ['one more string','15'], 'type': 'two'}

更新

我发现我的列表中有不止一项,例如:['first', 'second string']?我怎样才能返回['first', len_1, 'second string', len_2]

【问题讨论】:

    标签: python json python-3.x loops dictionary


    【解决方案1】:

    你可以使用append():

    lst = [
        {"data": ["string"], "type": "one"},
        {"data": ["a string "], "type": "one"},
        {"data": ["another string"], "type": "three"},
    ]
    
    def count_chars(e):
        return len(e)
    
    for d in lst:
        d["data"].append(count_chars(d["data"][0]))
    
    print(lst)
    # [{'data': ['string', 6], 'type': 'one'}, {'data': ['a string ', 9], 'type': 'one'}, {'data': ['another string', 14], 'type': 'three'}]
    

    如果列表中有更多字符串,可以使用extend() 并重建一个新列表:

    lst = [
        {"data": ["string", "hi"], "type": "one"},
        {"data": ["a string "], "type": "one"},
        {"data": ["another string"], "type": "three"},
    ]
    
    def count_chars(e):
        return len(e)
    
    for d in lst:
        newlst = []
        for x in d["data"]:
            newlst.extend([x, count_chars(x)])
        d["data"] = newlst
    
    print(lst)
    # [{'data': ['string', 6, 'hi', 2], 'type': 'one'}, {'data': ['a string ', 9], 'type': 'one'}, {'data': ['another string', 14], 'type': 'three'}]
    

    注意:由于count_chars() 只返回len(),因此只调用len() 本身可能更容易。

    【讨论】:

      【解决方案2】:

      应该可以的:)

      def count_chars(e):
          return len(e)
      
      a_lis = []
      with open('../JSON_FILE.json','r') as fa:
          a = json.load(fa)
          for e in a['entries']:
              for String in e["data"]: # Grab one string inside the strings list.
                  if type(String) == int:
                      continue # Skip the count chars value that you appended.
                  Length = count_chars(String) # Apply the function.
                  e["data"].append(Length) # Append the returned value to the data list containing the string.
      
              # Now we reorder the list from ["a", "ab", "abc", 1, 2, 3] to ["a", 1, "ab", 2, "abc", 3]
              strings_found = int(len(e["data"])/2)
              reordered_list = []
      
              for start in range(0, strings):
                  reordered_list = reordered_list + [x for x in e["data"][start::strings_found ]]
              e["data"] = reordered_list
      

      【讨论】:

      • 如果我的列表中有多个元素怎么办?例如:['first', 'second string']?我怎样才能返回['first', len_1, 'second string', len_2]
      • 我得到:TypeError: object of type 'int' has no len()
      • 我错了,现在它正确地跳过了数字。虽然它导致['first', 'second string', len_1, len_2]
      • 感谢您的帮助
      • 确实如此,谢谢。我使用enumerate() 只处理所有其他元素并跳过附加的长度,但我发现type()==int 最后更方便并忘记删除枚举。
      猜你喜欢
      • 2019-03-10
      • 2019-12-05
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      相关资源
      最近更新 更多