Check For The Existence Of A String In A List Of Tuples By Specific Index
If I have: my_list = [('foo', 'bar'), ('floo', 'blar')] how can I easily test if some string is in the first element in any of those tuples? something like: if 'foo' in my_list w
Solution 1:
If you want to check only against the first item in each tuple:
if'foo' in (item[0] foritemin my_list)
Alternatively:
ifany('foo' == item[0] for item in my_list)
Solution 2:
You can first extract a list of only the first items and then perform a check:
>>>my_list = [('foo', 'bar'), ('floo', 'blar')]>>>'foo'inlist(zip(*my_list))[0]
True
Alternatively:
>>> 'foo'innext(zip(*my_list))
True
Solution 3:
Use the batteries:
importoperatorif'foo'in map(operator.itemgetter(0), my_list):
This won't create a copy of your list and should be the fastest.
Solution 4:
if'foo' in map(lambda x: x[0], my_list):
<do something>
map
takes each element in the list, applies a function to it, and returns a list of the results. In this case, the function is a lambda function that just returns the first sub element of the original element.
((0,1),(3,4))
becomes (0,3)
.
Solution 5:
my_list = iter(my_list)
result = FalsewhileTrue:
try:
x, y = my_list.next()
if x == 'foo':
result = Truebreakexcept StopIteration:
break
Post a Comment for "Check For The Existence Of A String In A List Of Tuples By Specific Index"