简体   繁体   English

在列表列表中,将每个第二个元素除以每个第三个元素,python

[英]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.

相关问题 如何在python中用数字将列表列表中的每个元素除 - how to divide each element in a list of lists by a number in python 按每个列表中的第二个元素对列表字典进行排序 - Sort dictionary of lists by the second element in each list 将python中两个列表中的每个元素相乘 - Multiplying each element in two list of lists in python 如何将列表中的每个元素按第一个元素划分 - How to divide each element in list by first element 从每个列表中删除第三个元素,然后查找第二个列表中最后一个元素在特定范围内的列表 - Removing third element and second from each list and finding lists which have last elements within specific range in a 2D list Python:将每个元素的不同列表列表连接到一个列表列表中 - Python: Join each element different lists of lists in one list of lists 他们有什么方法可以将列表的每个元素与python上另一个列表的每个元素分开 - Is their any way that can divide each element of a list with each element of another list on python Python - 获取列表列表中每个列表的最后一个元素 - Python - get the last element of each list in a list of lists 如何将列表中的每个元素除以该列表中的每个元素 - How to divide each element in a list by every element of that list 将列表的每个元素与第二个列表的每个元素联系在一起 - Concat each element of list with each element of second list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM