Rating two or more lists

Howdy, codeboys and codegirls!

I ran into a simple problem, a seemingly simple solution. But, being a neophyte of Python, I feel that somewhere there is a better approach.

Say you have a list of mixed strings. There are two main types of strings in a bag: in them - = (a = potato) and without them (Lady Jane). You need to sort them by two lists.

The obvious approach is as follows:

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

Is there any other, more elegant way in it? Sort of:

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

but to sort by multiple lists?

But what if you have several data types?

+5
source share
9 answers

Try

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

or (holy freak)

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

: , append() .

+4

itertools.groupby() :

import itertools
f = lambda x: '=' in x
groups = itertools.groupby(sorted(data, key=f), key=f)
for k, g in groups:
    print k, list(g)
+4

. ( ), Pythonic , for. ( ) , , .

+3
def which_list(s):
    if "=" in s: 
        return 1
    return 0

lists = [[], []]

for arg in arguments:
    lists[which_list(arg)].append(arg)

plain, equal = lists

, if which_list lists .

+2

, .

equal = [arg for arg in arguments if '=' in arg]
plain = [arg for arg in arguments if '=' not in arg]
+2

- , , ( ).

, uniques , , .

uniques = set('= ')
matches = dict((key, []) for key in uniques)

for arg in args:
    key = set(arg) & uniques
    try:
        matches[key.pop()].append(arg)
    except KeyError:
        # code to handle where arg does not contain = or ' '.

, arg. Ie, arg, 'John= equalspace'. , , - ( KeyError).

+2

- filter, .
:

>>> l = ['a=s','aa','bb','=', 'a+b']
>>> l2 = filter(lambda s: '=' in s, l)
>>> l3 = filter(lambda s: '+' in s, l)
>>> l2
['a=s', '=']
>>> l3
['a+b']
+1

I put it together, and then I saw that Ned Batchelder was already in the same vein. However, I decided to pack a splitting method instead of a list, and just use the implicit 0/1 values ​​for False and True.

def split_on_condition(source, condition):
    ret = [],[]
    for s in source:
        ret[condition(s)].append(s)
    return ret

src = "z=1;q=2;lady jane;y=a;lucy in the sky".split(';')

plain,equal = split_on_condition(src, lambda s:'=' in s)
+1
source

Your approach is the best. For sorting only in two lists, it cannot become more understandable. If you want it to be single-line, encapsulate it in a function:

def classify(arguments):
    equal, plain = [], []
    for arg in arguments:
        if '=' in arg:
            equal.append(arg)
        else:
            plain.append(arg)
    return equal, plain


equal, plain = classify(lst)
+1
source

All Articles