How to split a list based on a condition?
good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
is there a more elegant way to do this?
That code is perfectly readable, and extremely clear!
# files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
Again, this is fine!
There might be slight performance improvements using sets, but it's a trivial difference, and I find the list comprehension far easier to read, and you don't have to worry about the order being messed up, duplicates being removed as so on.
In fact, I may go another step "backward", and just use a simple for loop:
images, anims = [], []
for f in files:
if f.lower() in IMAGE_TYPES:
images.append(f)
else:
anims.append(f)
The a list-comprehension or using set()
is fine until you need to add some other check or another bit of logic - say you want to remove all 0-byte jpeg's, you just add something like..
if f[1] == 0:
continue
Split list based on condition in Python
Using itertools.groupby
Ex:
from itertools import groupby
mylist = [2, 3, 4, 0, 0, 0, 6, 7, 8, 0, 4, 9, 0, 2, 0, 2, 0, 20, 0]
result = [list(v) for k, v in groupby(mylist, lambda x: x!=0) if k]
print(result)
Output:
[[2, 3, 4], [6, 7, 8], [4, 9], [2], [2], [20]]
Slicing a list into sublists based on condition
I've quickly written one way to do this, I'm sure there are more efficient ways, but this works at least:
num_list =[97, 122, 99, 98, 111, 112, 113, 100, 102]
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 - 1] < num_list[i]: # 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)
Hopefully this helps you a bit :)
Split data in list based on condition
Here you go:
import numpy as np
data = np.array(['A1', 'C3', 'B2', 'A2', 'D3', 'C2', 'A3', 'D2', 'C1', 'B1', 'D1', 'B3'])
# define some condition
condition = ['B', 'D']
boolean_selection = [np.any([ c in d for c in condition]) for d in data]
split1 = data[boolean_selection]
split2 = data[np.logical_not(boolean_selection)]
Python3: How can I split a list based on condition?
Use itertools.groupby
with a custom key function that changes every time we see a new header. In this function, we increment ctr
.
from itertools import groupby
lis = ['>a', 'b', 'c', '>d', 'e', '>f', '>g']
def group_by_header(lis: list):
def header_counter(x: str):
if x.startswith('>'):
header_counter.ctr += 1
return header_counter.ctr
header_counter.ctr = 0
return groupby(lis, key=header_counter)
print([list(l) for k, l in group_by_header(lis)])
# [['>a', 'b', 'c'], ['>d', 'e'], ['>f'], ['>g']]
Split list of tuples into seprate list based on a condition
I here post the solution of @Mustafa Aydin so that other users can find the solution soon.
inds, = np.nonzero(np.array(a)[:, 0] == 1)
[sub.tolist() for sub in np.split(a, inds) if sub.size]
Related Topics
Retrieve Links from Web Page Using Python and Beautifulsoup
Meaning of @Classmethod and @Staticmethod For Beginner
How to Install Python Packages [Ssl: Tlsv1_Alert_Protocol_Version]
Importerror: No Module Named 'Pygame'
What's the U Prefix in a Python String
Return, Return None, and No Return At All
Valueerror: Invalid Literal For Int() With Base 10: ''
Difference Between Numpy.Array Shape (R, 1) and (R,)
How to Apply a Function to Two Columns of Pandas Dataframe
Is There a Portable Way to Get the Current Username in Python
Use Numpy Array in Shared Memory For Multiprocessing
Append Existing Excel Sheet With New Dataframe Using Python Pandas
How to Get the Value of a Variable Given Its Name in a String