How do you split a list by condition in python?

Inspired by @gnibbler's great [but terse!] answer, we can apply that approach to map to multiple partitions:

from collections import defaultdict

def splitter[l, mapper]:
    """Split an iterable into multiple partitions generated by a callable mapper."""

    results = defaultdict[list]

    for x in l:
        results[mapper[x]] += [x]

    return results

Then splitter can then be used as follows:

>>> l = [1, 2, 3, 4, 2, 3, 4, 5, 6, 4, 3, 2, 3]
>>> split = splitter[l, lambda x: x % 2 == 0]  # partition l into odds and evens
>>> split.items[]
>>> [[False, [1, 3, 3, 5, 3, 3]], [True, [2, 4, 2, 4, 6, 4, 2]]]

This works for more than two partitions with a more complicated mapping [and on iterators, too]:

>>> import math
>>> l = xrange[1, 23]
>>> split = splitter[l, lambda x: int[math.log10[x] * 5]]
>>> split.items[]
[[0, [1]],
 [1, [2]],
 [2, [3]],
 [3, [4, 5, 6]],
 [4, [7, 8, 9]],
 [5, [10, 11, 12, 13, 14, 15]],
 [6, [16, 17, 18, 19, 20, 21, 22]]]

Or using a dictionary to map:

>>> map = {'A': 1, 'X': 2, 'B': 3, 'Y': 1, 'C': 2, 'Z': 3}
>>> l = ['A', 'B', 'C', 'C', 'X', 'Y', 'Z', 'A', 'Z']
>>> split = splitter[l, map.get]
>>> split.items[]
[1, ['A', 'Y', 'A']], [2, ['C', 'C', 'X']], [3, ['B', 'Z', 'Z']]]

In this short tutorial we will learn how to divide a Python list objects to multiple sublists.

Example list object

All examples in this tutorial will be based on the following programming languages list :

all_lang_lst = ['R', 'Julia', 'Python', 'Haskell', 'Java', 'Javascript']

Divide a list based with delimiter

In this simple case, the after being split, the elements will be written to a string delimited by commas followed by a space:

', '.join [all_lang_lst]

The output will be:

'R, Julia, Python, Haskell, Java, Javascript'

Split a list by condition

We might want to split a list into multiple sub lists based on a simple condition.

data_lang = ['R', 'Julia', 'Python']
other_lang = ['Java', 'Javascript', 'Haskell']
data_lst = []
other_lst = []

# divide the list values using comprehensions
data_lst = [x for x in all_lang_lst if x in data_lang]
other_lst = [x for x in all_lang_lst if x in other_lang]

#print the lists
print ["The data science related languages are:" + str[data_lst]]
print ["The other languages are: " + str[other_lst]]


Here’s the output:

The data science related languages are:['R', 'Julia', 'Python']
The other languages are: ['Haskell', 'Java', 'Javascript']

Note: as shown above we can use the join[] function to convert any list to a string.

Split Python lists by substring

In a similar fashion we can divide the list based on whether its element contains a specific sub string. We’ll start by defining a function:

def splt_by_substrng [my_lst, my_str]:
    subs_lst = []
    subs_lst_other =[]
    for e in my_lst:
        if my_str in e:
            subs_lst.append[e]
        else:
            subs_lst_other.append[e]
    return subs_lst, subs_lst_other

We’ll now call the function that we have just defined. In our case we would like to split programming languages containing the substring ‘ja’ into a separated list. The function will return two lists.

print["Here are the split lists: " + str[splt_by_substrng[all_lang_lst , "Ja"]]]

The result will be:

Here are the split lists: [['Java', 'Javascript'], ['R', 'Julia', 'Python', 'Haskell']]

Find the difference between two lists

Another way to split lists is simply by subtracting. We can convert our lists to Python sets and simply subtract them:

other_lst= set[all_lang_lst]- set[data_lang]

Sometimes, we want to split a list based on a condition with Python.

In this article, we’ll look at how to split a list based on a condition with Python.

How to split a list based on a condition with Python?

To split a list based on a condition with Python, we can use list comprehension.

For instance, we write

good = [x for x in mylist if x in goodvals]
bad  = [x for x in mylist if x not in goodvals]

to create the good list with the values in the goodvals list with

[x for x in mylist if x in goodvals]

Likewise, we create the bad list with the values that aren’t in goodvals with

[x for x in mylist if x not in goodvals]

Conclusion

To split a list based on a condition with Python, we can use list comprehension.

Web developer specializing in React, Vue, and front end development.

View Archive

How do you slice a list based on condition in Python?

Use if-else statements to split a list based on condition.
a_list = [1, 2, 3, 4].
even = [].
odd = [].
for item in a_list:.
if item % 2 == 0:.
even. append[item].
odd. append[item].

How do you split based on conditions?

split[] , to split the list into an ordered collection of consecutive sub-lists..
maintain elements' relative order [hence, no sets and dictionaries].
evaluate condition only once for every element [hence not using [ i ] filter or groupby ].

How do you split a list in Python?

Python String split[] Method The split[] method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a list by value in Python?

Let's discuss a certain way in which list split can be performed. This problem can be solved in two parts, in first part we get the index list by which split has to be performed using enumerate function. And then we can join the values according to the indices using zip and list slicing.

Chủ Đề