【问题标题】:Combine two lists of different length python合并两个不同长度的python列表
【发布时间】:2018-11-12 22:45:12
【问题描述】:

我有这个代码:

L = [1, x, x**2]
L2 = [1, 2*x]
def my_mul(x,y):
    if x == None: return y
    if y == None: return x
    return x*y
map(my_mul, L, L2)

这产生了我想要的,它是 L 和 L2 的元素乘积。

[1, 2*x^2, x^2]

但是有没有更 Pythonic 的方式来实现这一点?

具体来说,我可以在不定义自己的函数的情况下做到这一点吗?

【问题讨论】:

    标签: python-2.7 list sage


    【解决方案1】:

    下面的代码应该可以实现你所需要的

    import itertools
    import operator
    
    l1 = [1, 2, 3]
    l2 = [1, 2, 3, 4]
    
    list(itertools.starmap(operator.mul, itertools.zip_longest(l1, l2, fillvalue=1)))
    # result [1, 3, 9, 4]
    

    说明

    zip_longest 将压缩并填充较短列表中的缺失值:

    itertools.zip_longest(l1, l2, fillvalue=1)
    [(1, 1), (2, 2), (3, 3), (1, 4)]
    

    starmap 将乘法运算符应用于每个整数对

    【讨论】:

      猜你喜欢
      • 2017-11-30
      • 2017-12-04
      • 2019-10-16
      • 1970-01-01
      • 2020-06-27
      • 2017-12-24
      • 2017-12-29
      • 1970-01-01
      • 2021-11-19
      相关资源
      最近更新 更多