[英]Adding elements of list to list not working
我有一個包含清單的清單,
testList = [[1, 0, 1], [1, 1, 1], [0, 0, 0], ...]
我想要做的是將列表以n
組添加,因此如果n為2,則前兩個列表將被添加在一起,后兩個列表將被添加在一起,就像[1, 0, 1] + [1, 1, 1] = [2, 1, 2]
我嘗試了以下代碼,
group_len = 3
sumResultList = [[sum(x) for x in zip(*testList)] for group in [testList[i:i+group_len] for i in range(0, len(testList), group_len)]]
但是上面的代碼不起作用,我該如何解決?
l = [[1, 0, 1], [1, 1, 1],
[0, 0, 0], [1, 0, 1],
[1, 1, 1], [1, 0, 1],
[1, 1, 1], [1, 1, 1]]
n = 2
print [[sum(x) for x in zip(*l[a:a+n])] for a in range(0,len(l),n)]
輸出:
[[2, 1, 2], [1, 0, 1], [2, 1, 2], [2, 2, 2]]
嘗試這個:
testList = [[1, 0, 1], [1, 1, 1], [0, 0, 0], [2,3,4], [2,3,4], [2,3,4]]
group_len = 2
res = [list(map(sum, zip(*testList[k:k+group_len]))) for k in range(0, len(testList), group_len)]
print(res)
輸出:
[[2, 1, 2], [2, 3, 4], [4, 6, 8]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.