簡體   English   中英

如何使用二維數組每一行的元素壓縮一維數組中的每個元素?

[英]How to zip each element from a 1D array with the elements from each row of a 2D array?

我正在嘗試使用matplotlib繪制數據集,其中每個x包含多個y坐標。 要繪制它們,我必須組合這些數組以在單個圖中顯示它們。 如何使用來自二維數組每一行的元素(對應於一維數組元素的索引)壓縮一維數組中的每個元素? 不使用顯式 for 循環。 使用內置函數(例如 zip/list comprehension)甚至更好: numpy

轉向:

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

進入:

r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]

我想到了以下幾點:

  1. x擴展為與y相同的大小

  2. 壓平y

  3. 壓縮xy

如下

>>> x = [1, 2, 3]
>>> y = [[4, 5], [6, 7], [8, 9]]
>>> x = np.array(x).repeat(2)
>>> y = np.array(y).reshape(-1)
>>> list(zip(x, y))
[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]

我很想知道如何更有效地做到這一點。

請評論或回答更有效的方法。

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

result = [(i[0], i[1][0]) for i in zip(x,y)] + [(i[0], i[1][1]) for i in zip(x,y)]

輸出:

[(1, 4), (2, 6), (3, 8), (1, 5), (2, 7), (3, 9)]

通過方法5啟發這里

from functools import reduce

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

def listOfTuples(l1, l2): 
    l = list(map(lambda x, y:[(x,y[0]), (x,y[1])], l1, l2))
    m = reduce(lambda x, y: x + y, l)
    return(m)

r = listOfTuples(x, y)

[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]

repeatreshape方法的變體:

In [89]: x = [1, 2, 3] 
    ...: y = [[4, 5], [6, 7], [8, 9]]                                                          
In [90]: res = np.zeros((3,2,2),int)                                                           
In [91]: res[:,:,1]=y                                                                          
In [92]: res[:,:,0]=np.array(x)[:,None]                                                        
In [93]: res                                                                                   
Out[93]: 
array([[[1, 4],
        [1, 5]],

       [[2, 6],
        [2, 7]],

       [[3, 8],
        [3, 9]]])
In [94]: res.reshape(6,2)                                                                      
Out[94]: 
array([[1, 4],
       [1, 5],
       [2, 6],
       [2, 7],
       [3, 8],
       [3, 9]])

它使用broadcastingxy映射到res數組。

這僅使用迭代器,使用itertools.chain.from_iterable

import itertools

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

list(zip(list(itertools.chain.from_iterable(itertools.repeat(n, 2) for n in x)),
     list(itertools.chain.from_iterable(y))))

輸出

[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]

恕我直言,這在長期運行中應該更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM