【问题标题】:How to create a variable depth dictionary from a list or serie如何从列表或系列创建可变深度字典
【发布时间】:2021-12-08 15:04:09
【问题描述】:

我需要创建一个函数,让我可以创建一个包含不同长度的列表(或系列)项目的字典。这是我需要它的工作方式:

ex=[1,2,3,4]
unknownfunction(ex)
expected output: {1:{2:{3:4}}}

    
ex2=["a","b","c","d","e"]
unknownfunction(ex2)
expected output: {"a":{"b":{"c":{"d":"e"}}}}

希望你能帮我解决这个问题!

【问题讨论】:

    标签: python pandas dictionary nested series


    【解决方案1】:

    检查这个递归函数

    def func(arr):
        if len(arr) == 1:
            return arr[0]
        return {arr[0]: func(arr[1: ])}
    

    【讨论】:

      【解决方案2】:

      为了完整起见,这里是一个迭代解决方案:

      def makenest(seq):
          dct = seq[-1]
          for s in seq[-2::-1]:
              dct = { s: dct }
          return dct
      
      
      ex=[1,2,3,4]
      print(makenest(ex))
      #expected output: {1:{2:{3:4}}}
      
      ex2=["a","b","c","d","e"]
      print(makenest(ex2))
      #expected output: {"a":{"b":{"c":{"d":{"e"}}}}}
      

      【讨论】:

      【解决方案3】:

      您的 2 个示例有点不一致(第二个示例将 {"e"} 作为最后一个元素,与第一个相比),所以我不确定此任务的确切规格是什么,但这是一个解决方案第一个例子:

      from typing import List, Union, Dict
      
      def unknownfunction(x: List[Union[int, float, str]]) -> Dict:
          assert len(x) >= 2, "List must have at least 2 elements"
          a = x.pop()
          b = x.pop()
          dic = {b:a}
          while x:
              c = x.pop()
              dic = {c: dic}
          return dic
      

      【讨论】:

        【解决方案4】:

        这是我的解决方案;使用一些内置函数并利用 Python 的松散结构来创建通常在许多其他语言中无法实现或看到的东西,这又是另一种解决方法。

        现在,我不一定会提倡这种方法,因为它可能会导致在循环中更改变量类型引起一些混乱,但我只是认为这是一个很好的展示您在 Python 中 可以做什么 .不管是不是好主意。

        stackoverflow.py:

        def my_func(input: list) -> dict:
            output = input[len(input)-1]
            for index, item in enumerate(reversed(input)):
                if index == 0:
                    continue
        
                output = {item: output}
        
            return output
        

        test_stackoverflow.py:

        from stackoverflow import my_func
        
        
        def test_my_func_works_with_numbers():
            res = my_func([1, 2, 3, 4])
            assert res == {1: {2: {3: 4}}}
        
        
        def test_my_func_works_with_strings():
            res = my_func(["a", "b", "c", "d", "e"])
            assert res == {"a": {"b": {"c": {"d": "e"}}}}
        
        
        def test_my_func_works_with_combination():
            res = my_func([1, "a", 3, "b"])
            assert res == {1: {"a": {3: "b"}}}
        
        
        def test_my_func_works_with_only_one_entry():
            res = my_func([1])
            assert res == 1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-04-02
          • 2019-03-20
          • 2020-01-11
          • 1970-01-01
          • 2021-06-25
          • 1970-01-01
          • 2018-12-17
          • 1970-01-01
          相关资源
          最近更新 更多