By now I didn't find a convenient way to split a list by certain conditions, for example, I have a record list:
a = ((0,1),(1,0),(0,2),(1,0),(3,0),(4,0),(0,3),(1,5)....)
I want to split the content into 2 lists
alist = []
blist = []
for x in a:
if x[0] == 0:
alist.append(x)
elif x[0] == 1:
blist.append(x)
Not very concise.
Written as list comprehensions:
aList = [x for x in a if x[0] == 0]
bList = [x for x in a if x[0] == 1]
List comprehensions are usually good for reading and performance, but in this case the list must be iterated twice.
Is there a better way to do this job?
split() , to split the list into an ordered collection of consecutive sub-lists. E.g. split([1,2,3,4,5,3,6], 3) -> ([1,2],[4,5],[6]) , as opposed to dividing a list's elements by category.
A split function is composed of a specified separator and max parameter. A split function can be used to split strings with the help of a delimiter. A split function can be used to split strings with the help of the occurrence of a character. A split function can be used to split strings in the form of a list.
Use a comma to separate the items in a list. Before the final item in the list, the comma is replaced by the word 'and'. Use commas to separate adjectives when describing a noun.
Adding one line will make the loop more concise at the cost of readability (and FPness).
alist = []
blist = []
bothlists = [alist, blist]
for x in a:
bothlists[x[0]].append(x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With