python - Python equivalence for this c++ program
问题描述
I am having trouble solving problems in python because I can't find any equivalent for this while (getline()) in python. So even though I solve my problems they are not accepted because of the right way of taking input. How can I recode this in python? especially the while block!
#include <iostream>
#include <string>
using namespace std;
string sentences[105];
int main()
{
int pos = 0;
int longest = 0;
while (getline(cin, sentences[pos]))
{
if (sentences[pos].size() > longest)
longest = sentences[pos].size();
++pos;
}
for (int j = 0; j < longest; ++j)
{
for (int i = pos - 1; i >= 0; --i)
{
if (sentences[i].size() > j)
cout << sentences[i][j];
else
cout << ' ';
}
cout << '\n';
}
}
This is my python code.
while True:
try:
lst = []
n = 0
while True:
line1 = [' ']*100
line = input()
if n < len(line):
n = len(line)
for i in range(len(line)):
line1[i] = line[i]
if line:
lst.append(line1)
else:
break
for i in range(0,n):
x = ''
for j in range(len(lst)-1,-1,-1):
x += lst[j][i]
print(x)
except EOFError:
break
解决方案
在Python 2.7中,您有:
line = raw_input("Please input a new line: ")
在Python 3.5+中,您有:
line = input("Please input a new line: ")
两者都raw_input
返回input
一个字符串对象。您需要解析/扫描line
以检索您的数据。
MESSAGE = "Please input a new line: "
# I comprehend that `sentences` is a list of lines
sentences = []
longest = 0
line = input(MESSAGE)
while line:
# Loop continues as long as `line` is available
# Keep a track of all the lines
sentences.append(line)
# Get the length of this line
length = len(line)
if length > longest:
longest = length
for i in range(longest):
for j in range(len(sentences) - 1, -1, -1):
if len(sentences[j]) > i:
print(sentences[j][i])
line = input(MESSAGE)
推荐阅读
- angular - 如何正确连接可观察对象
- javascript - 如何更改 JSON 中的键值
- sql - 需要 T-SQL 查询帮助
- javascript - 约翰尼五到 arduino >>> 串行通信
- r - 如何使用 R 预测股票每天的未来价格?
- python - 如何使用 keras python 中的学习模型确定输入数据?
- javascript - 我想在用户单击注册按钮后记录用户输入的电子邮件值并选择菜单值到控制台?
- javascript - 表单提交后返回 false 不起作用
- excel - MS Access 导入 Excel 无法连接
- docker - Docker swarm 模式下 docker-compose.yml 中的 {{node.hostname}} 用法