As for your first question: "if item is in my_list:" is perfectly fine and should work if item equals one of the elements inside my_list. The item must exactly match an item in the list. For instance, "abc" and "ABC" do not match. Floating point values in particular may suffer from inaccuracy. For instance, 1 - 1/3 != 2/3.
As for your second question: There's actually several possible ways if "finding" things in lists.
Checking if something is inside
This is the use case you describe: Checking whether something is inside a list or not. As you know, you can use the in operator for that:
3 in [1, 2, 3] # => True
Filtering a collection
That is, finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that:
matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)
The latter will return a generator which you can imagine as a sort of lazy list that will only be built as soon as you iterate through it. By the way, the first one is exactly equivalent to
matches = filter(fulfills_some_condition, lst)
in Python 2. Here you can see higher-order functions at work. In Python 3, filter doesn't return a list, but a generator-like object.
Finding the first occurrence
If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else clause as well, which is not really well-known). You can also use
next(x for x in lst if ...)
which will return the first match or raise a StopIteration if none is found. Alternatively, you can use
next((x for x in lst if ...), [default value])
Finding the location of an item
For lists, there's also the index method that can sometimes be useful if you want to know where a certain element is in the list:
[1,2,3].index(2) # => 1
[1,2,3].index(4) # => ValueError
However, note that if you have duplicates, .index always returns the lowest index:......
[1,2,3,2].index(2) # => 1
If there are duplicates and you want all the indexes then you can use enumerate() instead:
[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]
If you want to find one element or None use default in next, it won't raise StopIteration if the item was not found in the list:
first_or_default = next((x for x in lst if ...), None)
How to get specific values from an element of the list
Get list item by attribute in Python - Stack Overflow
Python: get item from list in list - Stack Overflow
Get a key from a dictionary of lists by value of one of list's items
Hello everyone!
I have a document in Word that I've already parsed.
Here's how headings of that document look like in the list:
['Client Acceptance Screening Report on LTD Western Stream','Analysis of actual or alleged integrity issues','International blacklists, sanctions or other geopolitical concerns','Politically Exposed Persons (PEP)','Corporate details']
How can I get everything from the first element of the list after the word 'on'. I need to get the name of the legal entity which is LTD 'Western Stream'.
I tried this:
scanning = False
for i[0] in heading:
if i == 'o' and i+1 == 'n':
scanning = True
continue
if scanning == True:
print(i)But it doesn't work.
I also tried this, but it doesn't work either:
scanning = False
for i[0] in heading:
i[0] = q
if q == 'o' and q == 'n':
scanning = True
continue
if scanning == True:
print(q)I would be very grateful for the help.
Yes, you loop and compare:
items = [item for item in container if item.attribute == value]
And you get back a list which can be tested to see how many you found.
If you will be doing this a lot, consider using a dictionary, where the key is the attribute you're interested in.
If you do this it only gives the very first match, instead of comparing the whole list: find first sequence item that matches a criterion.
If you do something like this, you don't have to catch the exception but get None instead:
item = next((i for i in items if i == 'value'), None)
That's actually a triple-nested list, because range() returns a list, and then you have it wrapped in [].
Perhaps what you really wanted was...
mylist=[range(4*(x-1)+1,4*(x-1)+5) for x in range(1,5)]
At which point mylist[0][0] should do what you expect.
Hate to be the Captain Obvious, but all you needed to do is just go 1 level deeper :)
>>> mylist=[[range(4*(x-1)+1,4*(x-1)+5)]for x in range(1,5)]
>>> mylist
[[[1, 2, 3, 4]], [[5, 6, 7, 8]], [[9, 10, 11, 12]], [[13, 14, 15, 16]]]
>>> mylist[0][0][0]
1
The title's confusing, but hear me out. I have a dictionary set up like this:
{
"key1": ["value1", "value2"],
"key2": ["value3", "value4"],
etc.
}
Is there a way to retrieve a specific key by specifying only a single value from its associated list, i.e. get "key1" by specifying just "value2"? Every single key and value in the entire structure is unique.
So far, I've found this Stack Overflow article which explains how to look up keys by value:
mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)])
# Prints george...But it only works with flat dictionaries where values are just strings, not lists like in my case. I also could write a function that creates a new dictionary from the original one by manually iterating over it and skipping the unneeded values:
def invertDict(self, dict):
newDict = {}
for key, val in dict:
newVal = str(val[1])
newDict[newVal] = key
return newDictI also could just manually declare a dictionary where keys and values are reversed:
{
"value2": "key1",
"value4": "key2",
etc.
}But I only need to look it up once in the entire project, and it feels like defining a new dictionary, let alone a new function, just for one line is wasteful. There must be an elegant, pythonic way of doing this in one line, like it often is with Python, but so far I couldn't think of one. Any suggestions?
If I'm understanding your question correctly, you essentially want to select indexes from a list of lists, and create new lists from that selection.
Selecting indexes from a list of lists is fairly simple, particularly if you have a fixed number of selections:
parts = [(item[pos1], item[pos2]) for item in list]
Creating new lists from those selections is also fairly easy, using the built-in zip() function:
separated = zip(*parts)
You can further reduce memory usage by using a generator expression instead of a list comprehension in the final function:
def f( list, pos1, pos2 ):
partsgen = ((item[pos1], item[pos2]) for item in list)
return zip(*partsgen)
Here's how it looks in action:
>>> f( [['ignore', 'a', 1], ['ignore', 'b', 2],['ignore', 'c', 3]], 1, 2 )
[('a', 'b', 'c'), (1, 2, 3)]
Update: After re-reading the question and comments, I'm realizing this is a bit over-simplified. However, the general idea should still work when you exchange pos1 and pos2 for appropriate indexing into the contained array.
if i understand your question, something like the following should be easy and fast, particularly if you need to do this multiple times:
z = np.dstack([ arr for arr, time in lst ])
x, y = z[pos1], z[pos2]
for example:
In [42]: a = arange(9).reshape(3,3)
In [43]: z = np.dstack([a, a*2, a*3])
In [44]: z[0,0]
Out[44]: array([0, 0, 0])
In [45]: z[1,1]
Out[45]: array([ 4, 8, 12])
In [46]: z[0,1]
Out[46]: array([1, 2, 3])
Use operator.getitem:
import operator
operator.getitem(l, index)
Example:
>>> operator.getitem([1,2,3], 1)
2
I believe, though the other answers are correct, that he's probably needing to retrieve them using a callable. To that end, this works:
>>> from operator import itemgetter
>>> get1 = itemgetter(1)
>>> get1([0,1,2,3,4,5])
1
>>> get1('abcdefg')
'b'