嵌套用于+ =使用列表理解操作的循环

时间:2014-10-24 07:57:26

标签: python list list-comprehension

我的代码:

a = [[random.randint(0,10) for i in range(3)] for j in range(4)]
b = [0]*4
c = [random.random() for i in range(12)]
for i in range(len(a)):
    for j in a[i]:
        b[i] += c[j]

知道如何将其作为列表理解来实现吗?

3 个答案:

答案 0 :(得分:3)

使用sum

b = [sum(row) for row in a]

修改

b = [sum(c[i] for i in row) for row in a]

答案 1 :(得分:1)

试试这个代码段:

import operator

b = [sum(map(operator.getitem,[c]*3, a_)) for a_ in a]

operator.itemgetter

b = [sum(operator.itemgetter(*_a)(c)) for _a in a]

答案 2 :(得分:0)

对不起,这是你想要的吗?

import random

a = [[random.randint(0,10) for i in range(4)] for j in range(4)]
b = [0 for i in range(4)]

for i in a:
    for j in i:
        b[a.index(i)] += j

print b