是否有一种方法可以处理通过终端输入的数字整数列表,而不将其保存到列表中?

问题描述 投票:1回答:1

我正在尝试用Python编写类似的代码,但是我是新手。

int counts[] = { 0, 0, 0, 0, 0 };
for (int i = 0; i < groups; i++) {
    int groups_size;
    scanf(" %d", &groups_size);

    counts[groups_size] += 1;
}

请注意,并非所有数字都将其保存到内存中。

我试图在Python中以以下方式执行此操作:

for group in range(groups):
    num = int(input().strip())
    counts[num] += 1

这不起作用。当我在终端输入1 2 3 4 5时,我会得到ValueError: invalid literal for int() with base 10: '1 2 3 4 5'

在Python中是否有和在C中相同的方法?

python c python-3.x code-translation
1个回答
1
投票

在python中,它不会自动取一个数字,然后为另一个循环。您的input()命令将一次读取整行。因此,您可以做的是读取字符串中的整行,然后将其拆分为列表,如下所示-

str = input()
num = list(map(int,str.split()))

现在您将用户给定的所有输入存储在num变量中。您可以对其进行迭代,并按照以下步骤完成过程-

counts = [0]*5       #assuming you want it to be of size 5 as in your question
for inp in num :
    counts[inp] = counts[inp] + 1

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.