Home > Net >  splitting string list when eqal item is found on condition in python
splitting string list when eqal item is found on condition in python

Time:09-24

I'm trying to splitting the list when specific item found. So I can do with that using array if it is list of integers without any problem but want to do the same thing with list of stirings. Here is how I do that with a list of intergers(in here I take '5' as my specific number)

num_list =[0,1,2,3,4,5,1,2,3,4,5,2,3,4,5]
 
arrays = [[num_list[0]]] # array of sub-arrays (starts with first value)
 
for i in range(1, len(num_list)): # go through each element after the first
    if num_list[i] != 5: # If it's larger than the previous
        arrays[len(arrays)-1].append(num_list[i]) # Add it to the last sub-array
    else: # otherwise
        arrays.append([num_list[i]]) # Make a new sub-array 
print(arrays)

output:

[[0, 1, 2, 3, 4], [5, 1, 2, 3, 4], [5, 2, 3, 4], [5]]

I want to do this same thing with list of strings.

CodePudding user response:

The easiest option is just to walk through the list, 'resetting' each time you hit the special string:

my_list = ['apple', 'banana', 'cherry', 'apple', 'pine_apple']

out = []
y = []    
for i in my_list:
    if y and i == "apple":
        out.append(y)
        y = []
    y.append(i)

out.append(y)

print(out)
# [['apple', 'banana', 'cherry'], ['apple', 'pine_apple']]

# Or with different input:
# my_list = ['a', 'b', 'apple', 'c', 'd', 'apple', 'apple', 'e']
# [['a', 'b'], ['apple', 'c', 'd'], ['apple'], ['apple', 'e']]

CodePudding user response:

Try this:

def list_splitter(text_list, split_key):
    arrays = [[text_list[0]]] # array of sub-arrays (starts with first value)
    for i in range(1, len(text_list)): # go through each element after the first
        if text_list[i] != split_key: # If it's larger than the previous
            arrays[len(arrays)-1].append(text_list[i]) # Add it to the last sub-array
        else: # otherwise
            arrays.append([text_list[i]]) # Make a new sub-array 

    return arrays

text_lists = [["apple", "banana", "cherry","apple","pine_apple"], ['apple', 'apple', 'apple','apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple']]

for text_list in text_lists:
    print("The original list : "   str(text_list))

    res = list_splitter(text_list, 'apple')
    print("The list after splitting by a value : "   str(res))

Output:

The original list : ['apple', 'banana', 'cherry', 'apple', 'pine_apple']
The list after splitting by a value : [['apple', 'banana', 'cherry'], ['apple', 'pine_apple']]
The original list : ['apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple']
The list after splitting by a value : [['apple'], ['apple'], ['apple'], ['apple'], ['apple'], ['apple'], ['apple'], ['apple'], ['apple'], ['apple'], ['apple'], ['apple']]
  • Related