0

***我没有很好地解释这一点,所以希望这个编辑更有意义:基本上我必须编写适用于大量测试用例的代码,下面的输入只是一个示例。所以我不能手动将输入输入到我的函数中

假设我有以下输入:

    0
    4
    0,2,2,3

我需要生成某种输出,例如

    1

我怎样才能做到这一点?

我的意思是,如果我通常遇到问题,我可以定义一个函数,然后手动输入值,但是我如何读取原始数据(对数据执行一系列函数/操作)?

(对于作业,我应该在 STDIN 上接收输入 -> 并在 STDOUT 上打印正确的输出

4

5 回答 5

2

STDIN 只是一个由sys.stdin;表示的文件(或类似文件的对象)。您可以将其视为普通文件并从中读取数据。你甚至可以迭代它;例如:

sum = 0
for line in sys.stdin:
    item = int(line.strip())
    sum += item
print sum

要不就

entire_raw_data = sys.stdin.read()
lines = entire_raw_data.split()
... # do something with lines

此外,您可以迭代调用raw_input()返回发送到 STDIN 的连续行,甚至将其转换为迭代器:

for line in iter(raw_input, ''):  # will iterate until an empty line
    # so something with line

这相当于:

while True:
    line = raw_input()
    if not line:
        break
    # so something with line

另见:https ://en.wikibooks.org/wiki/Python_Programming/Input_and_output

于 2013-10-05T20:40:33.657 回答
2

我们可以很容易地使用raw_input()这种情况:

text_input = raw_input("Enter text:")

如果您使用的是 Python 3,则可以input()以相同的方式使用:

text_input = input("Enter text:")

或者,如果您更喜欢使用命令行参数运行程序,请使用sys.argv

import sys
for i in sys.argv:
    if i >= 1:
        command = i
        #do something with your command

这是一个很好的阅读:http ://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch06s03.html

编辑

好吧,只要理解这里真正的问题。

简单的方法:您将数据存储在一个文本文件中,然后用您的程序读取它。

f = open("path/to/command.txt", 'r')
commmands = f.read()

这样您就可以快速处理数据。处理后,您可以将其写入另一个文件:

output_file = open("path/to/output.txt", 'w')
output_file.write(result)

至于如何处理你的命令文件,你可以自己构造它并用str.split()方法处理它,并循环它。

Tips:所以不要忘记关闭文件,建议使用with语句:

with open('file.txt', 'w') as f:
   #do things
   f.write(result)

更多关于文件处理:

http://docs.python.org/3.3/tutorial/inputoutput.html#reading-and-writing-files

希望有帮助!

于 2013-10-05T20:48:18.593 回答
1

使用这个 raw_input() 它是基本的 python 输入函数。

myInput = raw_input()

有关原始输入的更多信息,请参阅:

http://docs.python.org/2/library/functions.html#raw_input

于 2013-10-05T20:39:37.383 回答
1

通常你想做:

the_input = input(prompt)        # Python 3.x

或者

the_input = raw_input(prompt)        # Python 2.x

接着:

print(output)        # Python 3.x

或者

print output        # Python 2.x

但是,您也可以(但可能不想)这样做:

import sys
the_input = sys.stdin.readline()
bytes_written = sys.stdout.write(output)

这或多或少是在幕后做什么print和做什么。, (and ) 就像文件一样工作 - 你可以读取和写入它们等。在 Python 术语中,它们被称为类文件对象。inputsys.stdinsys.stdoutsys.stderr

据我了解,你想要这样的东西:

def f(x, y, z):
    return 2*x + y + z + 1

a = int(input("Enter a number: "))        # presuming Python 3.x
b = int(input("Enter another number: "))
c = int(input("Enter the final number: "))
print(f(a, b, c))

如果运行,它看起来像这样:

>>> Enter a number: 7
>>> Enter another number: 8
>>> Enter the final number: 9
>>> 32
于 2013-10-05T20:41:54.843 回答
1

您可以使用该函数raw_input()从标准输入中读取,然后根据需要进行处理。

于 2013-10-05T20:30:52.383 回答