How to combine elements from two lists into a third?

前端 未结 6 1232
星月不相逢
星月不相逢 2020-12-06 04:09

I have two lists a and b:

a  =   [3,    6,   8,   65,   3]
b  =   [34,   2,   5,   3,    5]

c gets [3/34, 6/2, 8/5, 65/3, 3/5]


        
相关标签:
6条回答
  • 2020-12-06 04:28

    The built-in map() function makes short work of these kinds of problems:

    >>> from operator import truediv
    >>> a=[3,6,8,65,3]
    >>> b=[34,2,5,3,5]
    >>> map(truediv, a, b)
    [0.08823529411764706, 3.0, 1.6, 21.666666666666668, 0.6]
    
    0 讨论(0)
  • 2020-12-06 04:29

    Use zip and a list comprehension:

    >>> a = [3,6,8,65,3]
    >>> b = [34,2,5,3,5]
    >>> [(x*1.0)/y for x, y in zip(a, b)]
    [0.08823529411764706, 3.0, 1.6, 21.666666666666668, 0.6]
    
    0 讨论(0)
  • 2020-12-06 04:30

    You can use the following code:

    a  =   [3,    6,   8,   65,   3]
    b  =   [34,   2,   5,   3,    5]
    
    c = [float(x)/y for x,y in zip(a,b)]
    print(c)
    
    0 讨论(0)
  • 2020-12-06 04:51

    You can do this using list comprehension (element by element):

    div = [ai/bi for ai,bi in zip(a,b)]
    

    Note that if you want float division, you need to specify this (or make the original values floats):

    fdiv = [float(ai)/bi for ai,bi in zip(a,b)]
    
    0 讨论(0)
  • 2020-12-06 04:54
    >>> from __future__ import division # floating point division in Py2x
    >>> a=[3,6,8,65,3]
    >>> b=[34,2,5,3,5]
    >>> [x/y for x, y in zip(a, b)]
    [0.08823529411764706, 3.0, 1.6, 21.666666666666668, 0.6]
    

    Or in numpy you can do a/b

    >>> import numpy as np
    >>> a=np.array([3,6,8,65,3], dtype=np.float)
    >>> b=np.array([34,2,5,3,5], dtype=np.float)
    >>> a/b
    array([  0.08823529,   3.        ,   1.6       ,  21.66666667,   0.6       ])
    
    0 讨论(0)
  • 2020-12-06 04:54

    Using numpy.divide

    c=np.divide(a,b)
    
    0 讨论(0)
提交回复
热议问题