个向量的元素以产生第三个

个向量的元素以产生第三个

本文介绍了交叉连接 2 个向量的元素以产生第三个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个向量,并希望将一个向量分布到另一个向量以形成第三个向量,例如:

I have 2 vectors and want to distribute one across the other to form a third vector like:

V1 = (a,b,c)
V2 = (d,e,f)

结果:

V3 = (ad,ae,af,bd,be,bf,...cf) 'nine total elements

我知道怎么做的唯一方法是循环.我尝试了多种不同的搜索方式,但找不到一行代码"的解决方案,以避免循环.

The only way I know how to do it is by looping. I've tried searching a number of different ways, and can't find a 'one line of code' solution, to avoid looping.

如果我错过了,请指点我.我可能没有找到正确的搜索参数.

If I've missed it, please point me to it. I may have not found the right search parameters.

如果这是不可能的,请原谅我的痛苦并让我知道:,,,(.

If it is not possible, please spare me my misery and let me know :,,,(.

如果有答案,请分享.

推荐答案

你没有说清楚操作 ab 是什么意思.我在这里假设您想将两个实数相乘.

You do not make clear what operation ab means. I'll assume here you want to multiply two real numbers.

在 Python 中,您可以使用推导式.这是一个完整的代码片段.

In Python, you can use a comprehension. Here a complete code snippet.

v1 = (2, 3, 5)
v2 = (7, 11, 13)
v3 = tuple(x * y for x in v1 for y in v2)

v3 的值是

(14, 22, 26, 21, 33, 39, 35, 55, 65)

随心所欲.如果你想要一个 Python 列表,代码看起来更简单:使用

as wanted. If you want a Python list, the code looks easier: use

v3 = [x * y for x in v1 for y in v2]

很明显如何将操作更改为连接或任何其他所需的操作.下面是字符串连接的示例代码:

It will be obvious how to change the operation to concatenation or anything else desired. Here is sample code for concatenation of strings:

v1 = ('a', 'b', 'c')
v2 = ('d', 'e', 'f')
v3 = tuple(x + y for x in v1 for y in v2)

结果

('ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf')

您也可以使用 itertools 模块中的 product()(我在本答案的第一个版本中使用了该模块),但上面的方法似乎更容易.

You could also use product() from the itertools module (which I used in the first version of this answer) but the above seems easier.

这篇关于交叉连接 2 个向量的元素以产生第三个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 00:01