我需要創建一個函式,讓我創建一個字典,其中包含不同長度的串列(或系列)專案。這是我需要它的作業方式:
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"}}}}
希望你能幫我解決這個問題!
uj5u.com熱心網友回復:
檢查這個遞回函式
def func(arr):
if len(arr) == 1:
return arr[0]
return {arr[0]: func(arr[1: ])}
uj5u.com熱心網友回復:
為了完整起見,這是一個迭代解決方案:
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"}}}}}
uj5u.com熱心網友回復:
您的兩個示例有點不一致(與第{"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
uj5u.com熱心網友回復:
這是我的解決方案;使用一些內置函式并利用 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/330661.html
下一篇:創建按“組”分組的最短距離字典?
