我已经在Python工作了一段时间,我使用"try"和"except"解决了这个问题,但我想知道是否有另一种方法来解决它.
基本上我想创建一个这样的字典:
example_dictionary = {"red":[2,3,4],"blue":[6,7,8],"orange":[10,11,12]}
Run Code Online (Sandbox Code Playgroud)
所以,如果我有一个包含以下内容的变量:
root_values = [{"name":"red","value":2},{"name":"red","value":3},{"name":"red","value":4},{"blue":6}...]
Run Code Online (Sandbox Code Playgroud)
我实现example_dictionary的方法是:
example_dictionary = {}
for item in root_values:
try:
example_dictionary[item.name].append(item.value)
except:
example_dictionary[item.name] =[item.value]
Run Code Online (Sandbox Code Playgroud)
我希望我的问题很清楚,有人可以帮我解决这个问题.
谢谢.
我已声明以下类型:
type ExampleA = {
a: string;
}
type ExampleB = {
b: number;
}
type ExampleC = {
c: boolean;
}
type Examples = ExampleA &
ExampleB &
ExampleC;
Run Code Online (Sandbox Code Playgroud)
然后我使用如下类型:
function foo(pattern: { [key: string]: string }) {
console.log(pattern);
}
const bar: Examples = { a: 'foo', b: 1, c: false };
foo(bar);
Run Code Online (Sandbox Code Playgroud)
打字稿编译器在调用foo(bar)方法时不会抛出任何错误,即使bar:Examples变量与函数签名不匹配foo.
打字稿为什么不抛出任何错误?这是编译器中的错误吗?