![](/img/trans.png)
[英]How to turn multiple lists into a list of sublists where each sublist is made up of the same index items across all lists?
[英]What are all the ways that a list of lists or multiple lists can be combined elementwise - operate on the items from each list with the same index?
我有一個列表列表,並希望對元素進行操作,將具有相同索引的項目組合在一起。
a = [[1,2,3],
[4,5,6],
[7,8,9]]
# or
b = [['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9']]
對a[0][i]
、 a[1][i]
、 a[2][i]
。
new = [f(a[0][0],a[1][0]a[2][0]),
f(a[0][1],a[1][1],a[2][1]),
f(a[0][2],a[1][2],a[2][1])]
其中f
是任何接受適當參數的函數。
嘗試為多個類似問題制定規范。 隨意添加我忽略的答案。
首先使用 zip 來組合項目。
多個列表。
>>> list(zip(['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']))
[('1', '4', '7'), ('2', '5', '8'), ('3', '6', '9')]
使用zip(*thelist)
- rows,columns -> columns,rows - 轉置列表列表 -
a = [[1,2,3],
[4,5,6],
[7,8,9]]
>>> list(zip(*a))
[(1, 4, 7),
(2, 5, 8),
(3, 6, 9)]
b = [['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9']]
>>> list(zip(*b))
[('1', '4', '7'),
('2', '5', '8'),
('3', '6', '9')]
完成后,您可以迭代和組合。 都有一個相似的模式:調用傳遞組合值的函數/方法。
求和數
>>> [sum(thing) for thing in zip(*a)]
[12, 15, 18]
>>> list(map(sum, zip(*a)))
[12, 15, 18]
添加/連接/連接字符串
>>> [''.join(thing) for thing in zip(*b)]
['147', '258', '369']
>>> list(map(''.join, zip(*b)))
['147', '258', '369']
將字符串列表與數字列表相結合。
>>> x = ['a', 'b', 'c']
>>> y = [1,2,3]
>>> z = ['g', 'e', 'h']
>>> [''.join(str(item) for item in thing) for thing in zip(x,y,z)]
['a1g', 'b2e', 'c3h']
>>> [''.join(map(str,thing)) for thing in zip(x,y,z)]
['a1g', 'b2e', 'c3h']
將函數應用於元素列表。
>>> def f(args):
... a,b,c,*_ = args
... return (a+b)**c
>>> [f(thing) for thing in zip(*a)]
[78125, 5764801, 387420489]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.