Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating into two or more lists

Tags:

python

list

Howdy, codeboys and codegirls!

I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere.

Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in them (a=potato) and ones without (Lady Jane). What you need is to sort them into two lists.

The obvious approach is to:

for arg in arguments:
   if '=' in arg:
       equal.append(arg)
   else:
       plain.append(arg)

Is there any other, more elegant way into it? Something like:

equal = [arg for arg in arguments if '=' in arg]

but to sort into multiple lists?

And what if you have more than one type of data?

like image 337
Rince Avatar asked Sep 28 '09 11:09

Rince


1 Answers

Try

for arg in arguments:
    lst = equal if '=' in arg else plain
    lst.append(arg)

or (holy ugly)

for arg in arguments:
    (equal if '=' in arg else plain).append(arg)

A third option: Create a class which offers append() and which sorts into several lists.

like image 100
Aaron Digulla Avatar answered Oct 04 '22 20:10

Aaron Digulla