This question already has answers here:
How to reuse an expression in a comprehension expression?
(2 answers)
Closed 2 years ago.
I have a code that looks like this:
x = ["hello","world","if"]
test = [len(word) for word in x if len(word)>4]
print(test)
in my original code "len" is much complicated function, is there a way to do the calcualtion of len only once?
in a traditional for loop it can be done like this:
test = []
for word in x:
temp= len(word)
if temp > 4:
test.append(temp)
can you please advise how to achieve the same result without using a traditional for loop.
Thanks
You can use := operator (in case of Python 3.8+):
def my_len(s):
# ...other complicated computations...
return len(s)
x = ["hello","world","if"]
test = [l for word in x if (l:=my_len(word))>4]
print(test)
Note: don't overwrite default built-in functions, in this case len(). Other functions may depend on it.
Related
This question already has answers here:
How do Python's any and all functions work?
(10 answers)
Closed 3 years ago.
Just thought I would specify in the title, because I have found the latter all over the internet, but not the former. I am curious how to get a conditional that contains a list comprehension working in python. Specifically, I am curious about how to do something like the following:
if (abs(value - any_x)) > 100 for any_x in x:
Essentially, I want the program to proceed if the absolute value of the difference between the value and any value in the x array is greater than 100. But the syntax as it stands is incorrect. What exactly am I missing? Thanks and best regards,
-AA
Use any:
if any(abs(value - any_x) > 100 for any_x in x):
...
Don't use a list comprehension here as any will return True on the first True value it finds. Thus providing it a generator is the most efficient method as it will be lazily evaluated.
You can use any.
if any(abs(value - any_x) > 100 for any_x in x):
Pretty simple,
True in [abs(k-value)>100 for k in x]
This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 3 years ago.
Say that you had this:
Laugh = 'hehe'
The practicality of this of example doesn't really matter but if you wanted to put laugh into a list by doing: laugh = list(laugh) and you do laugh[1] = 'a'. How would you put laugh into 'hahe'?
In general, to convert a list into a string, use ''.join:
laugh = 'hehe'
laugh = list(laugh)
laugh[1] = 'a'
laugh = ''.join(laugh)
This is better than other methods such as using a for-loop:
new_laugh = ''
for c in laugh:
new_laugh += c
The simplest way (using just the + operator - in case you want to have a user defined function to do get the task done) would be to add the components of the list into one string:
def string_to_list(L):
S = ""
for i in L:
S = S + str(L)
return S
string_to_list(laugh)
You can also use the join() function, to do the same:
Laugh = ''.join(laugh)
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 7 years ago.
Here is what I would like to be able to do:
I have a file called functions, with lots of functions. The functions are all essentially the same, functionally speaking (i.e., they are all of the form: pandas.Dataframe -> pandas.Dataframe). Obviously, they do different things to the Dataframe, so in that sense they are different.
I'd like to be able to pass my main function a list of strings, which would be the actual function names in the module, and have my program translate the strings into function calls.
So, basically, instead of:
functions = [module.functionA, module.functionB, module.functionC]
x = g(functions)
print(x)
> 'magical happiness'
I would have:
function_strings = ['functionA','functionB','functionC']
functions = interpret_strings_as_function_calls(module,function_strings)
x = g(functions)
print(x)
> 'magical happiness'
Is there a way to do this? Or do I need to write a function in the module that matches each string with it's corresponding function? i.e.:
def interpret_strings(function_string):
if function_string == 'functionA':
return module.functionA
elif function_string == 'functionB':
return module.functionB
etc.
(or in a switch statement, or whatever)
You can use getattr(module, function_string).
This question already has answers here:
Check if all elements in a list are identical
(30 answers)
Closed 8 years ago.
I am trying to compare elements of a list u for equality.
A possible solution could be all(x == u[0] for x in u[1:]), or simply all(x == u[0] for x in u), but it looks rather weird.
In Python, it's possible to write a == b == c, with its usual "mathematical" meaning. So I thought I could, with the help of the operator module, write operator.eq(*u). However, the eq function takes only two arguments. Of course, functools.reduce(operator.eq, u) is of no use here, since after the first test eq(u[0], u[1]), I get a boolean, and it will fail when doing the second test, eq(<bool>, u[2]).
Is there a better way than the solution above? A more... "pythonic" way?
len(set(u)) == 1 is pretty Pythonic.
This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed last month.
How might I compress an if/else statement to one line in Python?
An example of Python's way of doing "ternary" expressions:
i = 5 if a > 7 else 0
translates into
if a > 7:
i = 5
else:
i = 0
This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I'm not sure it helps that much in creating readable code.
The readability issue was discussed at length in this recent SO question better way than using if-else statement in python.
It also contains various other clever (and somewhat obfuscated) ways to accomplish the same task. It's worth a read just based on those posts.
Python's if can be used as a ternary operator:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
Only for using as a value:
x = 3 if a==2 else 0
or
return 3 if a==2 else 0
There is the conditional expression:
a if cond else b
but this is an expression, not a statement.
In if statements, the if (or elif or else) can be written on the same line as the body of the block if the block is just one like:
if something: somefunc()
else: otherfunc()
but this is discouraged as a matter of formatting-style.