My code:
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]
Any idea how to implementing this as a list comprehension?
Use sum
:
b = [sum(row) for row in a]
b = [sum(c[i] for i in row) for row in a]
Try this snippet:
import operator
b = [sum(map(operator.getitem,[c]*3, a_)) for a_ in a]
Or with operator.itemgetter
:
b = [sum(operator.itemgetter(*_a)(c)) for _a in a]
Sorry, is this following what you want?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.