[英]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?
I have a list of lists and would like to operate on the items elementwise, combining items 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']]
Operate on a[0][i]
, a[1][i]
, a[2][i]
.对
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])]
Where f
is any function that accept appropriate arguments.其中
f
是任何接受适当参数的函数。
Attempt to make a canonical for multiple similar questions.尝试为多个类似问题制定规范。 Feel free to add answers that I have overlooked.
随意添加我忽略的答案。
Start by using zip to combine the items.首先使用 zip 来组合项目。
Multiple lists.多个列表。
>>> list(zip(['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']))
[('1', '4', '7'), ('2', '5', '8'), ('3', '6', '9')]
Transposing a lists of list using zip(*thelist)
- rows,columns -> columns,rows -使用
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')]
Once you have done that you can iterate and combine.完成后,您可以迭代和组合。 All have a similar pattern: call a function/method passing the combined values.
都有一个相似的模式:调用传递组合值的函数/方法。
Summing numbers求和数
>>> [sum(thing) for thing in zip(*a)]
[12, 15, 18]
>>> list(map(sum, zip(*a)))
[12, 15, 18]
adding/concatenating/joining strings添加/连接/连接字符串
>>> [''.join(thing) for thing in zip(*b)]
['147', '258', '369']
>>> list(map(''.join, zip(*b)))
['147', '258', '369']
Combining list of strings with list of numbers.将字符串列表与数字列表相结合。
>>> 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']
Apply function to list of list elementwise.将函数应用于元素列表。
>>> 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.