tags:

views:

115

answers:

4

hi,

I'd like to achieve following effect

a=[11, -1, -1, -1]
msg=['one','two','tree','four']
msg[where a<0]
['two','tree','four']

In similar simple fashion (without nasty loops).

PS. For curious people this if statement is working natively in one of functional languages.

//EDIT

I know that below text is different that the requirements above, but I've found what I wonted to acheave. I don't want to spam another answer in my own thread, so I've also find some nice solution, and I want to present it to you.

filter(lambda x: not x.endswith('one'),msg)
+10  A: 

You can use list comprehensions for this. You need to match the items from the two lists, for which the zip function is used. This will generate a list of tuples, where each tuple contains one item from each of the original lists (i.e., [(11, 'one'), ...]). Once you have this, you can iterate over the result, check if the first element is below 0 and return the second element. See the linked Python docs for more details about the syntax.

[y for (x, y) in zip(a, msg) if x < 0]

The actual problem seems to be about finding items in the msg list that don't contain the string "one". This can be done directly:

[m for m in msg if "one" not in m]
Lukáš Lalinský
Still learning, but can you explain this lovely bit of code?
Dominic Bou-Samra
I've added some more info and a link to the manual.
Lukáš Lalinský
@Lukas-could you also append the finished solution which I've introduced, in my own comment under my post?
bua
Good answer, Lukáš. Unfortunately our edits crossed. (See the revision history.)
Stephan202
Thanks for the fixes. :)
Lukáš Lalinský
How I create "a" list is:a=map(lambda x: string.find(x,'one'),msg)would You propose something more relevant?
bua
a = [m.find('one') for m in msg] or directly [m for m in msg if 'one' not in m]
Lukáš Lalinský
ok many thanks and +1 for You for whole support
bua
+2  A: 
[m for m, i in zip(msg, a) if i < 0]
SilentGhost
Think you have a typo there, SilentGhost - the second 'for' should be an 'in'
Andre Miller
thanks, Andre, well caught
SilentGhost
+1  A: 

The answers already posted are good, but if you want an alternative you can look at numpy and at its arrays.

>>> import numpy as np
>>> a = np.array([11, -1, -1, -1])
>>> msg = np.array(['one','two','tree','four'])
>>> a < 0
array([False,  True,  True,  True], dtype=bool)

>>> msg[a < 0]
array(['two', 'tree', 'four'], dtype='|S4')

I don't know how array indexing is implemented in numpy, but it is usually fast and problably rewritten in C. Compared to the other solutions, this should be more readable, but it requires numpy.

dalloliogm
A: 

I think [msg[i] for i in range(len(a)) if a[i]<0] will work for you.

Prabhu
that's just baaaad.
SilentGhost
Pls enlighten me.. It wud be very helpful
Prabhu