在Python中,如何在循环内的同一行中获取输入?

0 人关注

如何在同一行中给出元素的数量和列表?下面是一个例子。

234 567 321 345 123 110 767 111

在这里,我想问用户他/她想要多少个元素,也就是N,在指定之后,我想让用户在他/她输入N的同一行中输入元素。

T = int(input())
for x in range(T):
    N = int(input())
    nums = list(map(int, input().split()))

在这段代码中,我可以在不同的行中给出N和nums,但我希望它们在同一行中,然后评估解决方案。 以下是完整的代码。

def largest(num):
    num_str = str(num)
    i = 9
    while i >= 0:
        if str(i) in num_str:
            return i
        i -= 1
def smallest(num):
    num_str = str(num)
    i = 0
    while i <= 9:
        if str(i) in num_str:
            return i
        i += 1
def pairs(num):
    if num == 2:
        return 1
    if num == 3:
        return 2
    return 0
T = int(input())
for x in range(T):
    N = int(input())
    nums = list(map(int, input().split()))
    assert(len(nums) == N)
    bitscore = [""]*N
    for i in range(len(bitscore)):
        curr_score = str(11 * largest(nums[i]) + 7 * smallest(nums[i]))
        if len(curr_score) > 2:
            curr_score = curr_score[-2:]
        bitscore[i] = curr_score
    odd_pos_freq = [0] * 10
    even_pos_freq = [0] * 10
    for i in range(len(bitscore)):
        index = int(bitscore[i][0])
        if (i + 1) % 2 == 0:
            even_pos_freq[index] += 1
        else:
            odd_pos_freq[index] += 1
    count_pairs = [0] * 10
    for i in range(10):
        if even_pos_freq[i] <= 1 and odd_pos_freq[i] <= 1:
            continue
        count_pairs[i] += pairs(even_pos_freq[i]) + pairs(odd_pos_freq[i])
        count_pairs[i] = min(2, count_pairs[i])
    print(sum(count_pairs))

我知道这个问题可能听起来很愚蠢,但很多时候我都被这种小事卡住了,即使有正确的逻辑,我也无法提交正确的答案。

2 个评论
如果用户输入的内容少于他/她所指定的内容,你想怎么做?
你可以只读一行的N和所有的数字,然后把它们分开。索引0是N。
python
python-3.x
list
loops
user-input
Codenoob
Codenoob
发布于 2020-07-18
1 个回答
Pramote Kuacharoen
Pramote Kuacharoen
发布于 2020-07-18
已采纳
0 人赞同

替换你的代码。

N = int(input())
nums = list(map(int, input().split()))

with: