简体   繁体   中英

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]] ?

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; 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 .

you can first convert the whole list to a numpy array and then just zip the results in a single line as follows

result = list(map(list,zip(arr[:,0], arr[:,1].astype(float)/arr[:,2].astype(float))))

if you want integer results replace float by int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM