How can I apply a math operation on a list of tuples with `map()`?

后端 未结 2 1539
一向
一向 2021-01-28 06:35

I have a list of tuples

b = [(\'676010\', \'5036043\'), (\'771968\', \'4754525\'), (\'772025\', \'4754525\'), (\'772072\', \'4754527\'), (\'772205\', \'4754539\'         


        
相关标签:
2条回答
  • 2021-01-28 07:15
    >>> map(lambda x: tuple([float(x[0])/100000, float(x[1])/100000]), b)
    [(6.7601, 50.36043), (7.71968, 47.54525), (7.72025, 47.54525), (7.72072, 47.54527), (7.72205, 47.54539), (7.72276, 47.54542), (7.72323, 47.54541), (6.47206, 50.36049)]
    >>>
    
    0 讨论(0)
  • 2021-01-28 07:20

    Give map a function that operates on each tuple:

    map(lambda t: (float(t[0]) / 100000, float(t[1]) / 100000), b)
    

    or even nest the map() functions:

    map(lambda t: map(lambda v: float(v) / 10000, t), b)
    

    where the nested map() returns a list instead of a tuple.

    Personally, I'd still use a list comprehension here:

    [[float(v) / 10000 for v in t] for t in b]
    

    Demo:

    >>> b = [('676010', '5036043'), ('771968', '4754525'), ('772025', '4754525'), ('772072', '4754527'), ('772205', '4754539'), ('772276', '4754542'), ('772323', '4754541'), ('647206', '5036049')]
    >>> map(lambda t: (float(t[0]) / 100000, float(t[1]) / 100000), b)
    [(6.7601, 50.36043), (7.71968, 47.54525), (7.72025, 47.54525), (7.72072, 47.54527), (7.72205, 47.54539), (7.72276, 47.54542), (7.72323, 47.54541), (6.47206, 50.36049)]
    >>> map(lambda t: map(lambda v: float(v) / 10000, t), b)
    [[67.601, 503.6043], [77.1968, 475.4525], [77.2025, 475.4525], [77.2072, 475.4527], [77.2205, 475.4539], [77.2276, 475.4542], [77.2323, 475.4541], [64.7206, 503.6049]]
    >>> [[float(v) / 10000 for v in t] for t in b]
    [[67.601, 503.6043], [77.1968, 475.4525], [77.2025, 475.4525], [77.2072, 475.4527], [77.2205, 475.4539], [77.2276, 475.4542], [77.2323, 475.4541], [64.7206, 503.6049]]
    
    0 讨论(0)
提交回复
热议问题