我需要进行一系列文本输入,并将它们与数字和某些格式组合在一起。问题在于,我不知道输入的系列将预先包含多少个元素。我知道对于一定数量的输入而言,这样做很容易,但是我需要一个可以迭代尽可能多的函数。
所以基本上我需要服用“苹果香蕉樱桃...”和“ 5” 并输出:
str('{"apple": 5, "banana": 5, "cherry": 5, "...": 5}')
这是我到目前为止所拥有的:
print("Enter fruits:")
fruits = [x for x in input().split()]
print("Enter Maximum Fruits per Day")
maxfruit = input()
def maxfruitfuncstep1(x,y):
return str('"' + x + '"' + ": " + y)
for i in fruits:
print("{" + maxfruitfuncstep1(i,maxfruit) + "}")
但这只是给我输出:
{"apple": 5}
{"banana": 5}
{"cherry": 5}
如何使功能在打印输出中水平运行?我尝试使用“,”。join,但这给了我
",a,p,p,l,e,",:, ,5
答案 0 :(得分:1)
这就是您想要的:
int load(std::string filename, GLfloat vertexArray[][3], GLuint faces[][3]) {
//open file
std::cout << " -- Read file started -- " << std::endl;
std::ifstream file(filename);
if (file.is_open())
{
std::cout << " --File Opened --" << std::endl;
std::string line;
int ln = 0;
int vertNum = 1; //starts at one as faces starts looking at index 1
int faceNum = 0;
while (getline(file, line))
{
//std::cout << "Reading Line: " << ln << " : " << line << std::endl;
ln++;
if (!line.empty())
{
if (line.at(0) == 'v')
{
float temp;
float temparr[3];
std::stringstream ss;
ss << line;
int i = 0;
std::string t;
while (!ss.eof()) {
ss >> t;
//std::cout << "Token: " << std::endl;
if (std::stringstream(t) >> temp && i <= 3) {
//std::cout << "Store: " << temp << std::endl;
temparr[i] = temp;
i++;
}
t = "";
}
if (true) //put out of bounds checking
{
for (int i = 0; i < 3; i++)
{
vertexArray[vertNum][i] = temparr[i];
}
}
else
{
std::cout << "ERROR: Could not add vertex to vertexArray" << std::endl;
return 0;
}
vertNum++;
}
if (line.at(0) == 'f')
{
int temp;
int temparr[3];
std::stringstream ss;
ss << line;
int i = 0;
std::string t;
while (!ss.eof()) {
ss >> t;
//std::cout << "Token: " << t << std::endl;
if (std::stringstream(t) >> temp && i <= 3) {
temparr[i] = temp;
i++;
}
t = "";
}
if (true) //put out of bounds checking here
{
for (int i = 0; i < 3; i++)
{
faces[faceNum][i] = temparr[i];
}
}
else
{
std::cout << "ERROR: Could not add face to faces" << std::endl;
return 0;
}
faceNum++;
}
}
}
file.close();
std::cout << "Done!" << std::endl;
return 1;
}
else
{
std::cout << " ERROR: Cannot open file " << filename << std::endl;
return -1;
}
另一个解决方案很简单:
fruits = ["apple", "banana", "cherry"]
maxfruit ="5"
print("{" + ", ".join(fruit + ": " + maxfruit for fruit in fruits) + "}")
答案 1 :(得分:0)
一种方法是:
fruits = ['banana', 'strawberry', 'cherry']
max_num = 5
from collections import defaultdict
result = defaultdict(dict)
for x in fruits:
result[x] = max_num
str(dict(result))
"{'banana': 5, 'strawberry': 5, 'cherry': 5}"