songdg
V2EX  ›  问与答

如何将数组按照正负分割成多个数组

  •  
  •   songdg · Jun 21, 2018 · 2009 views
    This topic created in 2892 days ago, the information mentioned may be changed or developed.

    array([ 0, 1, 2, 3, 2, 1, 0, -2, -3, -5, -7, -9, -8, -6, -5, -3, -1, 2, 3, 5, 7, 8, 6, 5, 7, 9, 11, 12, 14, 16, 13, 11, 9, 8, 7, 5, 4, 2, -1, -3, -6, -8, -11, -13, -16, -18]) 例如把以上数组划分成 4 个数组放进列表里 [array([ 0, 1, 2, 3, 2, 1, 0]),array([ -2, -3, -5, -7, -9, -8, -6, -5, -3, -1]),array([ 2, 3, 5, 7, 8, 6, 5, 7, 9, 11, 12, 14, 16, 13, 11, 9, 8, 7, 5, 4, 2]),array([ -1, -3, -6, -8, -11, -13, -16, -18])]

    2 replies    2018-06-22 04:59:15 +08:00
    ipwx
        1
    ipwx  
       Jun 21, 2018 via iPhone   ❤️ 1
    np.where
    msg7086
        2
    msg7086  
       Jun 22, 2018   ❤️ 1
    a = [0, 1, 2, 3, 2, 1, 0, -2, -3, -5, -7, -9, -8, -6, -5, -3, -1, 2, 3, 5, 7, 8, 6, 5, 7, 9, 11, 12, 14, 16, 13, 11, 9, 8, 7, 5, 4, 2, -1, -3, -6, -8, -11, -13, -16, -18]

    r = []
    a.each_with_index do |n, i|
    r << [] if i == 0 || a[i] >= 0 && a[i-1] < 0 || a[i] < 0 && a[i-1] >= 0
    r.last << n
    end

    r
    => [[0, 1, 2, 3, 2, 1, 0], [-2, -3, -5, -7, -9, -8, -6, -5, -3, -1], [2, 3, 5, 7, 8, 6, 5, 7, 9, 11, 12, 14, 16, 13, 11, 9, 8, 7, 5, 4, 2], [-1, -3, -6, -8, -11, -13, -16, -18]]
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2677 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 11:43 · PVG 19:43 · LAX 04:43 · JFK 07:43
    ♥ Do have faith in what you're doing.