将字典中键的值映射到它们自己的键



我有这个python字典

dct = {'A': ['B', 'C'], 'B': ['D'], 'D': ['E'], 'C': ['F'], 'E': ['G']}

我需要一个函数将其作为返回

(A(B(D(E(G)))))(C(F))

我无法将每个值的元素映射到它们自己的值。如有任何帮助,我们将不胜感激。

谢谢

我不擅长Python。我用Java开发了你想要的函数。希望您可以轻松地将其转换为Python。

import java.util.HashMap;
import java.util.Map;
public class MapTheMap {
// Count of open parentheses
static int parentheses = 0;
public static void main(String[] args) {
// Creating the map (i.e. dictionary in python)
Map<Character, Character[]> map = new HashMap<>();
map.put('A', new Character[]{'B', 'C'});
map.put('B', new Character[]{'D'});
map.put('D', new Character[]{'E'});
map.put('C', new Character[]{'F'});
map.put('E', new Character[]{'G'});
// The start key is A, you can develop a logic to get the first key if you want to
Character key = 'A';
System.out.print("(" + key);
recursion(map, key);
}
public static void recursion(Map<Character, Character[]> map, Character key) {
// If the map contains the key, add 1 parenthesis, print the value of that key, and call the function again with value as a key (Call 1: Key A -> Value B -- Call 2: Key B --> ...)
if (map.containsKey(key)) {
for (Character valueKey : map.get(key)) {
parentheses++;
System.out.print("(" + valueKey);
recursion(map, valueKey);
}
}
// If the map doesn't contain the key, print close parentheses 
else {
while (parentheses >= 0) {
System.out.print(")");
parentheses--;
}
}
}
}

如果你有什么不明白的地方,告诉我,我会尝试编辑答案。

最新更新