Cross Concatenate Elements of 2 Vectors to Produce a Third

后端 未结 3 764
余生分开走
余生分开走 2021-01-23 06:38

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)

Result:

V3          


        
3条回答
  •  盖世英雄少女心
    2021-01-23 06:53

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

    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)
    

    The value for v3 is then

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

    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)
    

    which results in

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

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

提交回复
热议问题