Say I have a list in python as
some_list = [(1,'a'),(2,'b')]
Is there a way I can shorten the following code:
def someMethod(some_list, some_string):
for value in some_list:
if 'some_string' is value[1]:
print 'do_something'
Say I have a list in python as
some_list = [(1,'a'),(2,'b')]
Is there a way I can shorten the following code:
def someMethod(some_list, some_string):
for value in some_list:
if 'some_string' is value[1]:
print 'do_something'
Use the any function:
def someMethod(some_list, some_string):
if any(x[1] == 'some_string' for x in some_list):
print 'do_something'
The any function returns true if any element of its argument is true. In this case, the argument is a generator which produces a sequence of Boolean values, so the entire list doesn't need to be examined: any will stop running the generator as soon as it finds a matching value.
Yes, you can flatten the list and check it at the same time.
def someMethod(some_list, some_string):
some_list = [value for item in some_list for value in item if value == some_string]
for _ in some_list:
print 'do_something'
If you are looking for shorter lengthwise, then you can do the following (less pythonic):
def someMethod(some_list, some_string):
some_list = [value for item in some_list for value in item if value == some_string]
for _ in some_list: print 'do_something'
I suppose this might be shorter:
def someMethod(some_list, some_string):
for value in itertools.ifilter(lambda x: x[1]=='some_string', some_list):
print 'do_something'
Or even:
def someMethod(some_list, some_string):
print '\n'.join('do_something' for x in some_list if x[1]=='some_string')
But, while some of the suggestions are shorter than your code, none of them are more clear. Clarity should be your goal here, not brevity.
You have a list of tuples and a string, and you want to do_something() every time the string appears in the second part of a tuple.
def someMethod(some_list, some_string):
[do_something() for _, s in some_list if s == some_string]
The trick is to get at the second part of the tuple by unpacking it into _, s, where _ is a throwaway variable.
Unfortunately you can't execute the statement print 'do_something' inside a list comprehension. However, you can call the print function, which will need to be explicitly imported if you're using Python 2:
from __future__ import print_function
def someMethod(some_list, some_string):
[print('do_something') for _, s in some_list if s == some_string]