Is there a way to have
statements = [statement1, statement2, statement3, ...]
in Python?
I want to be able to do:
run statements[i]
or:
f = statements[j] (where f is a function)
P.S. I want to have a list of assignment statements (lambda would not work) and I rather not create functions. For example:
switch = [output = input, output = 2 * input, output = input ** 2]
Is there any other way than defining a function for each entry?
Thank you everyone who answered my question.
Yes. Functions are first-class-citizens in python: i.e. you could pass them as parameters or even store them in an array.
It is not uncommon to have a list of functions:
You could build a simple registry in python like this:
#!/usr/bin/env python
processing_pipeline = []
def step(function):
processing_pipeline.append(function);
return function
#step
def step_1(data):
print("processing step1")
#step
def step_2(data):
print("processing step2")
#step
def step_3(data):
print("processing step3")
def main():
data = {}
for process in processing_pipeline:
process(data)
if __name__ == '__main__':
main()
Here the processing_pipeline is just a list with functions.
step is a so called decorator-function, which works like a closure.
The python interpreter adds while parsing the file every decorated #step to the pipeline.
And you are able to access the function with an iterator, or via processing_pipeline[i]: try adding processing_pipeline[2](data).
I want to be able to do: run statements[i]
well, you can do that by exec:
statements = ["result=max(1,2)","print(result)"]
for idx in range(len(statements)):
exec(statements[idx])
print(result)
Hope it helps!
This is perfectly fine:
def addbla(item):
return item + ' bla'
items = ['Trump', 'Donald', 'tax declaration']
new_items = [addbla(item) for item in items]
print(new_items)
It adds a political statement to every item in items :)
If you want to run a block of statements, use a function.
def run_statements():
func()
for i in range(3):
if i > 1:
break
extra_func()
run_statements()
If you want to choose specific statements from a list, wrap each one in a function:
def looper():
for i in range(3):
if i>1:
break
def func():
print('hello')
statements = [looper, func]
statements[-1]()
If your statements are simply function calls, you can put them directly into a list without creating wrapper functions.
You can do:
funcs = [min, max, sum]
f = funcs[0]
funcs[1](1,2,3) # out 3
funcs[2]([1,2,3]) # out 6
Since we've had every other way, I thought I'd toss this out:
def a(input):
return pow(input, 3)
def b(input):
return abs(input)
def c(input):
return "I have {0} chickens".format(str(input))
#make an array of functions
foo = [a,b,c]
#make a list comprehension of the list of functions
dop = [x(3) for x in foo]
print dop
Related
I'm only starting getting into a python from #C and I have this question that I wasn't able to find an answer to, maybe I wasn't able to form a question right
I need this to create two lists when using:load(positives) and load(negatives), positives is a path to the file. From #C I'm used to use this kind of structure for not copy the same code again just with another variable, eg. what if I would need 5 lists. With this code i'm only able to access the self.dictionary variable but in no way self.positives and self.negatives
I get error AttributeError: 'Analyzer' object has no attribute 'positives' at line 'for p in self.positives:'
MAIN QUESTION IS: how to make self.dictionary = [] to create list variables from the argument name - self.positives and self.negatives which i need later in code
def load(self, dictionary):
i = 0
self.dictionary = []
with open(dictionary) as lines:
for line in lines:
#some more code
self.dictionary.append(0)
self.dictionary[i] = line
i+=1
#later in code
for p in self.positives:
if text == p:
score += 1
for p in self.negatives:
if text == p:
score -= 1
#structure of a program:
class Analyzer():
def load()
def init()
load(positives)
load(negatives)
def analyze()
for p in self.positives
You cannot write self.dictionary and expect python to convert it to self.positives or self.negatives.
Instead of positives, insert self.positives and self.negatives into the function and use those.
Took long enough to figure it out:
All it took was to return a self.dictionary from load, and assign it in init as self.positives = self.load(positives):
#structure of a program:
class Analyzer():
def load()
return self.dictionary
def init()
self.positives = self.load(positives)
self.negatives = self.load(negatives)
def analyze()
for p in self.positives
From what I understood from the question, you are trying to create 2 lists. You first have to declare them like this:
FirstList = [ ]
SecondList = [ ]
Then take whatever value you want to add to the list and append it like this:
SecondList.append("The thing you want in the list")
by the end of the code your lists should be filled with what you want.
say I have a function that takes two argument, a list and a number:
def function1(list1,n):
#do something
Say that I also have another function defined later on:
def function2(list2,x):
#do something
I need to use the argument list1 inside the function2. How can I do that? I tried to save list1 as a variable using copy.deepcopy(), but it still gives me error. How can I do that?
Assuming you're modifying the list in f1, return list1 from f1:
def f1(list1, n):
# do something to the list and n
return list1
def f2(list2, n)
# do something
x = f1(list1, n)
f2(x, n)
I created a function that will inverse a list recursively but it uses an global list in witch it puts the elements.
Can this be rewritten so that it won't use an outside variable/list to achieve the same result.
Here is the code:
invs = []
def inv_list(list_, elem):
global invs
if elem is not None:
invs.append(elem)
if not list_:
return invs
else:
try:
el = list_.pop()
inv_list(list_, el)
except Exception:
pass
What about:
def inv_list(lst):
if not lst:
return []
return inv_list(lst[1:]) + lst[:1]
it looks like you are doing a whole lot more work than you need to
def reverse_recurse(a_list):
if not a_list:
return []
return [a_list.pop(),] + reverse_recurse(a_list)
While your implementation could be improved in various ways, when I find that I want to build something recursive without using globals and without making the interface feel dirty is create a nested helper function:
def inv_list(list_):
invs = []
def helper(elem):
if elem is not None:
invs.append(elem)
if not list_:
return invs
else:
try:
el = list_.pop()
return helper(el)
except Exception:
pass
return helper(None)
That way, you can have values that are at the scope of the outer function.
The problematic way to do it is simple, just use default arguments.
def rec_reverse(input=[], output=[]):
if len(input) == 0:
return
else:
output.append(input.pop())
rec_reverse(input, output)
return output
x = list(range(10))
y = list(range(20))
print(rec_reverse(x, []))
print(rec_reverse(y, []))
Just remember to pass a new list to the output, so that you can call it again without getting old values.
Nevertheless, you can use the safe approach without using default arguments:
def rec_reverse(input):
if not input:
return input
else:
return [input.pop(), ] + rec_reverse(input)
And you can also use its recursive equivalent as a lambda expression:
rec_reverse = lambda input=[]: [] if not input else [input.pop(), ] + rec_reverse(input)
Keep in mind though, that there's an even simpler solution without using recursion at all:
x = list(range(10))
rec_reverse = lambda input: input[::-1]
print(rec_reverse(x))
Since in Python, you can reverse any list using extended slice notation.
Also, you can just use reverse() and spare you the trouble.
def reverse(input):
input.reverse()
return input
Building on Rederick Deathwill, here is a simplified version of your function:
def inv_list(list_):
def inner(list_, invs):
if not list_:
return invs
else:
invs.append(list_.pop())
return inner(list_, invs)
return inner(list_, [])
It uses a default value for invs, getting rid of the need for a global variable to hold the inverted list. With subsequent invocation, invs is passed along so that the next call can build on it.
Once the bottom of the call stack is reached, the function returns the reversed list. A nice addition to the original is the return inner(list_, invs) line, which allows the caller to capture the new list as the return value.
This is not the shortest, but I think it is at least readable.
please keep in mind that while I showcase my code, that I am fairly new to programming. So please forgive any problems. I am writing a piece of python code that uses the output of one function and then averages it in another function. I am having troubling proceeding on how to do that, this is what I have so far:
def avg(A):
if not A:
return 0
return sum(A) / len(A)
Using the function above, I have to use it to calculate the average of the function produced below:
def SampleFunction(): # Example Function
A = list(range(300))
for i in range(300):
if i%2:
A[i] = 3.1*(i+1)**1.2 - 7.9*i
else:
A[i] = 4.2*(i+2)**.8 - 6.8*i
return A
Below this is a function I have trying to tie the two together.
def average(SampleFunction):
if len(SampleFunction) == 0: return 0
return sum(SampleFunction) / len(SampleFunction)
def avg(A):
if not A:
return 0
return sum(A) / len(A)
def SampleFunction(): # Example Function
A = list(range(300))
for i in range(300):
if i%2:
A[i] = 3.1*(i+1)**1.2 - 7.9*i
else:
A[i] = 4.2*(i+2)**.8 - 6.8*i
return avg(A) #Return the avg of A instead of just A
You are right at the moment of passing SampleFunction as parameter, but it's a function, you have to call invoke it inside average():
def average(some_function):
result = some_function() # invoke
return avg(result) # use the already defined function 'avg'
When you call it, pass the function you want to average():
print average(SampleFunction)
Note:
I would recommend you to follow Python naming conventions. Names like SomeName are used for classes, whereas names like some_name are used for functions.
I've got a main function in my python code and several other functions. In my main, I've accessed another function that creates a dictionary. At the end of my python code is an if statement that writes text into a text file. I'm having trouble figuring out how to access the dictionary created from the previous functions.
Here is a model of how my code currently works
def main:
# "does something"
call function X
# does other stuff
def X:
#create dictionary
dict = {'item1': 1,'item2': 2}
return dictionary
....
.... # other functions
....
if __name__ == "__main__":
# here is where I want to write into my text file
f = open('test.txt','w+')
main()
f.write('line 1: ' + dict[item1])
f.write('line 2: ' + dict[item2])
f.close()
I'm just starting to learn python so any help is much appreciated! Thank you!
You have to add parentheses () when defining functions, even if it does not take any arguments:
def main():
...
def X():
...
Also, because X() returns something, you have to assign the output to a variable. So you can do something like this in main:
def main():
mydict = X()
# You now have access to the dictionary you created in X
You can then return mydict if you want in main(), so you can use it at the end of your script:
if __name__ == "__main__":
f = open('test.txt','w+')
output = main() # Notice how we assign the returned item to a variable
f.write('line 1: ' + output[item1]) # We refer to the dictionary we just created.
f.write('line 2: ' + output[item2]) # Same here
f.close()
You can not define a variable in a function and then use it elsewhere outside of the function. The variable will only be defined in the local scope of the relative function. Thus, returning it is a good idea.
By the way, it's never a good idea to name a dictionary dict. It will override the built-in.