我有以下字符串 - 它们是赋值命令:
my_dict = dict(lnodenum = 134241, d1 = 0.200000, jobname = 'hcalfzp')
有没有办法将包含变量和值的字符串转换为字典的键和值?它等同于执行以下命令:
my_str = """lnodenum = 134241
d1 = 0.200000
jobname = 'hcalfzp' """
exec('my_dict = dict(%s)' % ','.join(my_str.split('\n')))
我想这是一种方法:
public static void main(String[] args){
//Declares my input variables and Scanner variable
String firstInput;
String secondInput;
String userProblem;
char operator;
//Creates the scanner
Scanner userInput = new Scanner(System.in);
//Asks for input
System.out.println("Please enter a problem you would like to calculate (ex. \"2.0 * 4.3\")");
userProblem = userInput.nextLine();
//Finds the doubles in the string and the operator
firstInput = userProblem.substring(0, 3);
secondInput = userProblem.substring(6, 9);
operator = userProblem.charAt(4);
//parses the strings to doubles
double firstNumber = Double.parseDouble(firstInput);
double secondNumber = Double.parseDouble(secondInput);
//Tests for the operator and executes accordingly
if(operator == '+'){
System.out.println(firstNumber + secondNumber);
}
else{
if(operator == '-'){
System.out.println(firstNumber - secondNumber);
}
else{
if(operator == '*'){
System.out.println(firstNumber * secondNumber);
}
else{
if(operator == '/'){
System.out.println(firstNumber / secondNumber);
}
else{
if(operator == '%'){
System.out.println(firstNumber % secondNumber);
}
else{
System.out.println("You did not input correctly");
}
}
}
}
}
}
不确定是否有人会想到更简洁的方式?
注意:我正在使用自己的代码进行科学计算,所以我不介意使用像恶意输入数据这样的安全问题的代码。但是,我更喜欢让代码更短更容易阅读:)
答案 0 :(得分:2)
不需要exec
。只需使用dict
函数的常规作业。
my_str = """lnodenum = 134241
d1 = 0.200000
jobname = 'hcalfzp' """
my_dict = dict(pair for pair in (line.strip().split(' = ') for line in my_str.splitlines()))
结果:
>>> my_dict
{'d1': '0.200000', 'lnodenum': '134241', 'jobname': "'hcalfzp'"}
或者,如果您想要解析每个对象,请使用ast.literal_eval
并理解:
import ast
my_dict = {k:ast.literal_eval(v) for k,v in (line.strip().split(' = ') for line in my_str.splitlines())}
结果:
>>> my_dict
{'d1': 0.2, 'lnodenum': 134241, 'jobname': 'hcalfzp'}