[英]In a list of lists divide each second element by each third element, python
In a list like在一个列表中
[['Austria', 200, 50], ['Australia', 50, 10]]
How can I divide each second element by each third element and get a result like如何将每个第二个元素除以每个第三个元素并得到类似的结果
[['Austria', 4], ['Australia', 5]]
? [['Austria', 4], ['Australia', 5]]
?
My workaround so far到目前为止我的解决方法
element0 = [[line[0],] for line in mylist]
element1 = [[float(line[1]),] for line in mylist]
element2 = [[float(line[2]),] for line in mylist]
division_np = np.array(element1)/np.array(element2)
division_np = division_np.tolist()
mergelists = list(zip(element0, division_np))
mergelists
But this looks way too much for such a simple task.但是对于这样一个简单的任务来说,这看起来太过分了。
You don't need to import numpy for this;您不需要为此导入 numpy; a simple list comprehension will do the job:
一个简单的列表理解就可以完成这项工作:
[ [country, numer/denom] for (country, numer, denom) in mylist]
Output:输出:
[['Austria', 4.0], ['Australia', 5.0]]
If you know you have/need integers, simply make the second value numer//denom
.如果您知道您有/需要整数,只需将第二个值
numer//denom
。
you can first convert the whole list to a numpy array and then just zip the results in a single line as follows您可以先将整个列表转换为 numpy 数组,然后将结果压缩在一行中,如下所示
result = list(map(list,zip(arr[:,0], arr[:,1].astype(float)/arr[:,2].astype(float))))
if you want integer results replace float by int.如果你想要整数结果用 int 替换 float。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.