哪个Python模块适合于列表中的数据操作?
我有一系列的x,y和z坐标,我需要对它们进行操作。它们位于三个元组的一个列表中,如{(x1,y1,z1),(x2,y2,z2),…} 我需要加法、乘法和对数来处理数据哪个Python模块适合于列表中的数据操作?,python,module,Python,Module,我有一系列的x,y和z坐标,我需要对它们进行操作。它们位于三个元组的一个列表中,如{(x1,y1,z1),(x2,y2,z2),…} 我需要加法、乘法和对数来处理数据 我想学习一个模块,它和Awk语言一样强大。我不确定你到底想要什么。你可以通过列表理解做很多事情。例如,如果要打开列表: coords = [(x1, y1, z1), (x2, y2, z2), (x3, y3, z3)] # etc 进入元组(x1+x2+x3,y1+y2+y3,z1+z2+z3),然后可以执行以下操作: s
我想学习一个模块,它和Awk语言一样强大。我不确定你到底想要什么。你可以通过列表理解做很多事情。例如,如果要打开列表:
coords = [(x1, y1, z1), (x2, y2, z2), (x3, y3, z3)] # etc
进入元组(x1+x2+x3,y1+y2+y3,z1+z2+z3)
,然后可以执行以下操作:
sums = (sum(a[0] for a in coords), sum(a[1] for a in coords), sum(a[2] for a in coords))
def prod(lst):
return [x*y*z for x, y, z in list(zip(*lst))]
coords = [(2, 4, 8), (3, 6, 5), (7, 5, 2)]
print(prod(coords))
>>> [42, 120, 80]
事实上,有经验的python程序员可能会这样写:
sums = map(sum, zip(*coords))
虽然这对初学者来说有点像魔术
如果要跨坐标相乘,则想法类似。唯一的问题是python没有与sum
等价的内置乘法。我们可以建立自己的:
import operator
def prod(lst):
return reduce(operator.mul, lst)
然后,可以按坐标方向将元组相乘,如下所示:
prods = map(prod, zip(*coords))
如果你想做一些更复杂的乘法(内积?),这将需要更多的工作(虽然这不会很困难)
我不确定你想取的对数是多少。但您可以在数学模块中找到log函数:
from math import log
希望这有帮助。在Python3中,
reduce
函数消失了。你可以做:
sums = (sum(a[0] for a in coords), sum(a[1] for a in coords), sum(a[2] for a in coords))
def prod(lst):
return [x*y*z for x, y, z in list(zip(*lst))]
coords = [(2, 4, 8), (3, 6, 5), (7, 5, 2)]
print(prod(coords))
>>> [42, 120, 80]
如果需要很多数组操作,那么numpy是python中的最佳选择
>>> import numpy
>>> data = numpy.array([(2, 4, 8), (3, 6, 5), (7, 5, 2)])
>>> data
array([[2, 4, 8],
[3, 6, 5],
[7, 5, 2]])
>>> data.sum() # product of all elements
42
>>> data.sum(axis=1) # sum of elements in rows
array([14, 14, 14])
>>> data.sum(axis=0) # sum of elements in columns
array([12, 15, 15])
>>> numpy.product(data, axis=1) # product of elements in rows
array([64, 90, 70])
>>> numpy.product(data, axis=0) # product of elements in columns
array([ 42, 120, 80])
>>> numpy.product(data) # product of all elements
403200
或数组的元素操作
>>> x,y,z = map(numpy.array,[(2, 4, 8), (3, 6, 5), (7, 5, 2)])
>>> x
array([2, 4, 8])
>>> y
array([3, 6, 5])
>>> z
array([7, 5, 2])
>>> x*y
array([ 6, 24, 40])
>>> x*y*z
array([ 42, 120, 80])
>>> x+y+z
array([12, 15, 15])
元素级数学运算,例如
>>> numpy.log(data)
array([[ 0.69314718, 1.38629436, 2.07944154],
[ 1.09861229, 1.79175947, 1.60943791],
[ 1.94591015, 1.60943791, 0.69314718]])
>>> numpy.exp(x)
array([ 7.3890561 , 54.59815003, 2980.95798704])
您不需要单独的库或模块来执行此操作。Python在语言中内置了列表理解,它允许您操作列表和执行计算。如果要进行大量的科学计算,或者要进行大量的数字运算,则可以使用numpy模块执行相同的操作。在python 3.0中,reduce函数位于functools模块中。