【问题标题】:Format one nested list style to match another list格式化一个嵌套列表样式以匹配另一个列表
【发布时间】:2018-10-03 18:53:49
【问题描述】:

我有 xy 坐标,我试图在 matplotlib 中匹配长度。我需要 x 值列表来匹配 y 值嵌套列表模式,这样图表就不会在列表之间画一条线,而是从每个嵌套列表开始和停止。

x(时间):

[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, ...]

y(相位)

[[1.0, 1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, ...]]

列表长度会有所不同,每个嵌套列表的长度也会有所不同。

【问题讨论】:

  • 所有嵌套列表的长度是否每个列表都相等?
  • 你试过什么?如果您需要嵌套x 列表,则遍历y 长度,并在x 中创建您的子列表。如果您需要 y 是一维的,那么只需将其展平(“展平”是您的搜索词)。
  • @chrisz:这就是为什么我没有像你那样立即去np.reshape:OP 在 y[0] 中显示 6,但在 y[1] 中显示 7+。
  • 是的,列表的长度总是匹配的,但是一旦我将 y 列表按其唯一编号嵌套,元素的长度就会改变,从而导致错误

标签: python list numpy matplotlib nested-lists


【解决方案1】:

您可以使用np.split,它在作为第二个参数提供的索引处分解数组或列表:

# create random example
>>> y = [list(np.random.randint(0, 10, (np.random.randint(3, 10),))) for j in range(10)]
>>> x = list(np.random.randint(0, 10, (sum(map(len, y)),)))
>>> y
[[6, 8, 4, 5], [1, 3, 6, 3, 7, 8], [1, 5, 9, 6, 4], [2, 7, 3], [8, 3, 6, 8], [0, 6, 4, 4, 6, 9], [5, 4, 8, 3, 8, 1], [6, 4, 7, 2], [2, 1, 0], [2, 2, 5, 7]]
>>> x
[6, 7, 3, 4, 1, 4, 4, 8, 2, 7, 0, 9, 8, 7, 9, 9, 6, 0, 5, 5, 2, 2, 5, 5, 4, 4, 5, 4, 2, 1, 4, 5, 3, 5, 0, 4, 7, 0, 4, 3, 3, 7, 7, 5, 3]

# split
>>> xs = np.split(x, np.cumsum(np.fromiter(map(len, y), int, count=len(y)-1)))
>>> xs
[array([6, 7, 3, 4]), array([1, 4, 4, 8, 2, 7]), array([0, 9, 8, 7, 9]), array([9, 6, 0]), array([5, 5, 2, 2]), array([5, 5, 4, 4, 5, 4]), array([2, 1, 4, 5, 3, 5]), array([0, 4, 7, 0]), array([4, 3, 3]), array([7, 7, 5, 3])]

【讨论】:

    【解决方案2】:

    如果您的列表是锯齿状的(假设元素总数相等),您可以迭代 y,并在迭代时从 x 创建块。

    x = [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
    y = [[1,1,1], [1,1,1,1], [1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1]]
    
    curi = 0
    fin = []
    for i in y:
      fin.append(x[curi:curi+len(i)])
      curi += len(i)
    
    print(fin)
    

    输出:

    [[2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2, 2], [2, 2, 2, 2, 2, 2, 2, 2, 2, 2], [2, 2, 2, 2, 2, 2, 2, 2]]
    

    如果您的列表不是锯齿状:

    x.reshape(y.shape)
    

    【讨论】:

    • 你能解释一下锯齿状是什么意思吗?
    • [[1,2,3], [1,2,3]] == 不锯齿,[[1], [1,2,3]] == 锯齿。基本上,如果任何子列表的长度不同
    • 谢谢!您的解决方案修复了我的列表格式。现在我只需要让 matplotlib 正确读取列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    相关资源
    最近更新 更多