ranjan das wrote:
I am facing the following problem


I have a list of the form

INPUT= [ [ ['A1-N','A2-Y','A3-N' ],['B1-Y','B2-N','B3-N' ] ], [.........] ]

and I want an output of the form (selecting only those elements which have a
Y associated with them)

OUTPUT=[ ['A2-Y', 'B1-Y'],[....] ]

Can the Y be anywhere, or must it be at the end of the string? Should 'Y2-N' be included or excluded? I will assume excluded.

What about lowercase 'y'? Should 'A3-y' be included? I assume it should be.



I wrote the following code. Although it gives me the desired output, it
CHANGES the list INPUT

Start with a simple function that extracts the strings you want from the inner-most list, Here's the hard way:

def select(items, suffix):
    suffix = suffix.upper()
    result = []
    for s in items:
        if s.upper().endswith(suffix):
            result.append(s)
    return result


This can be simplified to:

def select(items, suffix):
    suffix = suffix.upper()
    return [s for s in items if s.upper().endswith(suffix)]


Now you can use it:



OUTPUT = []
# INPUT looks like:
# [ [a1_list, b1_list, ...], [a2_list, b2_list, ...], ... ]
for middle in INPUT:
    # middle looks like [a99_list, b99_list, c99_list, ...]
    temp = []
    for inner in middle:
        # inner looks like [astr-N, bstr-Y, cstr-Y, ...]
        temp.extend(select(inner, '-Y'))
    OUTPUT.append(temp)


There is no need to make a copy of the input list.



--
Steven

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to