Python Forum
splitting numeric list based on condition
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
splitting numeric list based on condition
#3
you are very helpful! thank you very much.

(May-25-2019, 11:27 AM)michalmonday Wrote:
num_list = [0,1,2,3,4,5,1,2,3,4,5,2,3,4,5]
 
arrays = [[]] # array of sub-arrays

for i, num in enumerate(num_list):          # go through each element after the first
    arrays[-1].append(num)                  # Add it to the last sub-array
    if num == 5 and i != len(num_list)-1:   # if 5 encountered and not last element
        arrays.append([])
        
print(arrays)
Output:
[[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [2, 3, 4, 5]]
import numpy as np
num_arr = np.array([0,1,2,3,4,5,1,2,3,4,5,2,3,4,5])
arrays = np.split(num_arr, np.where(num_arr[:-1] == 5)[0]+1)
print(arrays)
Output:
[array([0, 1, 2, 3, 4, 5]), array([1, 2, 3, 4, 5]), array([2, 3, 4, 5])]

btw, could explain what is actually happening in this line of code, especially the last part [0]+1

arrays = np.split(num_arr, np.where(num_arr[:-1] == 5)[0]+1)
Reply


Messages In This Thread
RE: splitting numeric list based on condition - by python_newbie09 - May-25-2019, 05:45 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Numeric Enigma Machine idev 9 698 Mar-29-2024, 06:15 PM
Last Post: idev
  unable to remove all elements from list based on a condition sg_python 3 505 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Sent email based on if condition stewietopg 1 910 Mar-15-2023, 08:54 AM
Last Post: menator01
  create new column based on condition arvin 12 2,406 Dec-13-2022, 04:53 PM
Last Post: jefsummers
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 877 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  select Eof extension files based on text list of filenames with if condition RolanRoll 1 1,561 Apr-04-2022, 09:29 PM
Last Post: Larz60+
  Splitting strings in list of strings jesse68 3 1,829 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
Question Numeric Anagrams - Count Occurances monty024 2 1,539 Nov-13-2021, 05:05 PM
Last Post: monty024
  How to get datetime from numeric format field klllmmm 3 2,036 Nov-06-2021, 03:26 PM
Last Post: snippsat
  How to map two data frames based on multiple condition SriRajesh 0 1,521 Oct-27-2021, 02:43 PM
Last Post: SriRajesh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020