简体   繁体   English

在 python 中使用 sys.stdin.read() 进入 arguments 后应该按下什么按钮

[英]What button should be pressed after entering arguments with sys.stdin.read() in python

Iam working in a simple python code that uses sys library to get a multi-lines input through cmd, I am using sys.stdin.read() to enter my input like that:我正在使用一个简单的 python 代码,该代码使用 sys 库通过 cmd 获取多行输入,我正在使用 sys.stdin.read() 来输入我的输入:

3 50
60 20
100 50
120 30

then i don't know what to press to run the program.然后我不知道按什么来运行程序。

i tried pressing enter, Ctrl+D and Ctrl+z Nothing happened我试着按回车,Ctrl+D 和 Ctrl+z 什么都没发生

#Uses python3
import sys

def max_dot_product(a, b):
    a = sorted(a)
    b = sorted(b)
    res = 0
    for i in range(len(a)):
        res += a[i] * b[i]
    return res

if __name__ == '__main__':
    input = sys.stdin.read()
    data = list(input.split())
    n = data[0]
    a = data[1:(n + 1)]
    b = data[(n + 1):]
    print(max_dot_product(a, b))

The input works fine for me;输入对我来说很好; I used enter (optional) and ctrl-D after the last pair of values.我在最后一对值之后使用了enter (可选)和ctrl-D

From there, the program fails because you try to multiply strings.从那里开始,程序失败,因为您尝试将字符串相乘。 You have to convert the input to numeric.您必须将输入转换为数字。

data = list(map(int, input.split()))

Output: Output:

3 50
60 20
100 50
120 30
[3, 50, 60, 20, 100, 50, 120, 30]
9100

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM