开发者

Restricted Assignment in Python's List Comprehensions?

The example is stolen from here but my goal has a restriction so that output is [8,12,-54]. How can you do it with list comprehensions? I need to somehow refer to the index like x_{i}*y_{i}, I am hesitant to add a loop there, is there some elegant solution?

>>> vec1 = [2, 4, 6]
>>> vec2 = [4, 3, -9]
>>> [x*y for x in vec1 for y in vec2]
[8开发者_高级运维, 6, -18, 16, 12, -36, 24, 18, -54]


[x * y for x, y in zip(vec1, vec2)]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜