Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a list on a condition?

Tags:

python

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?

like image 334
Max Avatar asked Dec 31 '12 10:12

Max


People also ask

How do you split a list by condition in python?

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.

Can you use the split function with a list?

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.

How do you separate items in 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.


1 Answers

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)
like image 152
Ignacio Vazquez-Abrams Avatar answered Oct 06 '22 01:10

Ignacio Vazquez-Abrams