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