Hi,
since I wrote 2 articles where I used IloOplExec to call Python code from OPL
I was asked more, namely how to convert any OPL tuple set to Python
So let me show you.
tuple user
{
string name;
int age;
string city;
float speed;
}
{user} users={<"Alice",30,"Paris",1.2>,<"Bob",40,"London",4.6>};
execute
{
function getPythonListOfTuple(tupleSet)
{
var quote="\"";
var nextline="\\\n";
var nbFields=tupleSet.getNFields();
var res="[";
for(var i in tupleSet)
{
res+="{";
for(var j=0;j<nbFields;j++)
{
res+=quote+tupleSet.getFieldName(j)+quote;
res+=":";
var value=i[tupleSet.getFieldName(j)];
if (typeof(value)=="string") res+=quote;
res+=value;
if (typeof(value)=="string") res+=quote;
res+=",";
res+=nextline;
}
res+="},";
}
res+="]";
return res;
}
writeln(getPythonListOfTuple(users));
}
gives
[{"name":"Alice",\
"age":30,\
"city":"Paris",\
"speed":1.2,\
},{"name":"Bob",\
"age":40,\
"city":"London",\
"speed":4.6,\
},]
which can then be used in Python:
data=[{"name":"Alice",\
"age":30,\
"city":"Paris",\
"speed":1.2,\
},{"name":"Bob",\
"age":40,\
"city":"London",\
"speed":4.6,\
},]
for i in data:
print(i)
gives
{'name': 'Alice', 'age': 30, 'city': 'Paris', 'speed': 1.2}
{'name': 'Bob', 'age': 40, 'city': 'London', 'speed': 4.6}
regards
#DecisionOptimization#OPLusingCPLEXOptimizer