我试图将python中的"if else"语句转换为字典.
我试图将其转换为字典,但如何处理最后一个else子句?
val=3
if val==1:
print "a"
elif val==2:
print "b"
elif val==3:
print "c"
elif val==4:
print "d"
else:
print "value not found:"
print "===========Converted if else into dictionary ==================="
DATA_SOURCE = {1:"a",2:"b",3:"c",4:"d"}
print DATA_SOURCE[val]
Run Code Online (Sandbox Code Playgroud)
我已创建此代码作为替代:
if not DATA_SOURCE.has_key(val):
print "value not found:"
else:
print DATA_SOURCE[val]
Run Code Online (Sandbox Code Playgroud)
它是等同的吗?
我需要将类似的结构分配给另一个,只是名称不同.如果它具有相同的名称,我们可以直接使用=(赋值).我不想使用memcopy,因为它会复制位.
struct first {
int i;
char c;
};
struct second {
int i;
char c;
//we can overload assignment operator to copy field.
void operator = ( struct first& f) {
i=f.i;
c=f.c;
}
};
int main()
{
struct first f;
f.i=100;
f.c='a';
struct second s=f;
}
Run Code Online (Sandbox Code Playgroud)
但我收到编译错误.错误:请求从"第一个"转换为非标量类型"第二个".
不确定是否可能.