使用生成器填充二维数组中的整数值

问题描述 投票:0回答:2

我想使用下面的代码(我不应该使用map(),对于在线编程站点,因为它给出了错误:TypeError:'map'对象不可订阅):

arr[i][j] = [int(input("Input score").strip().split()[:l]) for j in range(n) for i in range(t)]

而不是以下工作版本:

for i in range(t):   
    for j in range(n):
        arr[i][j] = map(int, input("Input score").strip().split())[:l]

但错误是(假设如此)基于提供列表而不是单个值,如下所述:

TypeError:int()参数必须是字符串或数字,而不是'list'

无法通过任何替代方式找到解决方案,例如在第一步中将rhs(所需的soln。)转换为字符串,然后在第二步中分配给lhs;因为需要分配给arr [i] [j]。

附:需要使解决方案使用arr的单个和行的值,例如需要找到行的值和甚至单个值的总和。下面的代码使用行方式的arr值来填充总数。

for i in range(t): 
    for j in range(n):
        # Find sum of all scores row-wise 
        sum = 0
        for m in arr[i][j]:
            sum += m
        total[i][j] = sum
python-3.x
2个回答
1
投票

我们可以按如下方式进行嵌套列表理解:

t = int(input("Input number of tests: ")) 
n = int(input("Input number of rows: "))#.strip().split()) 

total = [[sum([int(i) for i in input("Input score: ").split()]) for j in range(n)] for t_index in range(t)]

print(total)

输入输出对的示例:

Input number of tests: 2
Input number of rows: 3
Input score: 1 2 3
Input score: 2 3 4
Input score: 3 4 5
Input score: 4 5 6
Input score: 5 6 7
Input score: 6 7 8
[[6, 9, 12], [15, 18, 21]]

2
投票

您可以映射嵌套的for循环:

for i in range(t):   
    for j in range(n):
        arr[i][j] = map(int, input("Input score").strip().split())[:l]

列表理解如:

arr = [map(int, input("Input score").strip().split())[:l] for i in range(t) for j in range(n)]

没有像map那样:

arr = [[int(k) for k in input("Input score").strip().split())[:l]] 
       for i in range(t) for j in range(n)]
© www.soinside.com 2019 - 2024. All rights reserved.