I'm not sure whether this kind of functionality exists or not or how is best to go about this. I am wanting to create a general problem solver where I can define the predicates, operations and such before solving rather than coding directly. So far I have been storing functions as part of a dictionary. The only way that it seems possible to do this with a dictionary is to create it with every potential combination imaginable.
For example, previously it was this:
self.Operators = {"STACK": self.stack, "UNSTACK": self.unstack,
"PICKUP": self.pickup, "PUTDOWN": self.putdown}
Where I would now like it to be something more like:
self.Operators = {("STACK", x, y): [[("clear", y), ("holding", x)], ["armempty", ("on", x, y)]]}
I know I am probably barking up the wrong tree with dictionaries here but this is the first time I've tried to do something like this and I have no idea what the appropriate/most Pythonesque way to manage this is?
I have solved this using the following (which is what I am going to go with):
self.Operators = {'PICKUP': [[['ontable', 'a'], ['armempty']], [['holding', 'a']]]}
The list that is then returned I parse using a list comprehension:
y = [w.replace("a", args[0]) for w in y]
For a list that has multiple variables, I will end up doing multiple list comprehensions by enumerating through characters.
Related
I have a function(x). I have also several dctionaries items that will go as function() argument x. I need to write a dynamic name for x using for loop. In PHP used to be simple, but here I cannot find a simple way. I see posts about creating new dictionaries etc. very complicated. Am I missing something? I thought Python was extra simplistic.
EDIT:
I need this in a dynamic way where a number is replaced with i:
for i in range(1, 100):
function(x1)
I cannot write function(x1), function(x2), function(x3) 99 times. How to incorporate i in a simple way without creating dictionaries or lists etc.
Maybe it is not possible the way I want, because x1, x2, x3, ... x99 are dictionaries and also object and cannot generate their names in a simple way taking x and adding i at the end to make it x1, can I?
EDIT ends.
I need to add i at the end or a dictionary name:
for i in range(1, 100):
z = 'n'+str(i) # or something like this
function(m.''.i) # this is only an attempt, which is incorrect.
As others have pointed out in comments, this is probably an indication that you need to refactor the rest of your code so that the data is passed as a list rather than 99 individual variables.
If you do need to access all the values like this, and they're fields on an object, you can use the getattr() function:
for i in range(1, 100):
z = 'n'+str(i)
function(getattr(m, z))
However, if at all possible, do modify the rest of the code so that the data is in a list or similar.
I want to perform calculations on a list and assign this to a second list, but I want to do this in the most efficient way possible as I'll be using a lot of data. What is the best way to do this? My current version uses append:
f=time_series_data
output=[]
for i, f in enumerate(time_series_data):
if f > x:
output.append(calculation with f)
etc etc
should I use append or declare the output list as a list of zeros at the beginning?
Appending the values is not slower compared to other ways possible to accomplish this.
The code looks fine and creating a list of zeroes would not help any further. Although it can create problems as you might not know how many values will pass the condition f > x.
Since you wrote etc etc I am not sure how long or what operations you need to do there. If possible try using list comprehension. That would be a little faster.
You can have a look at below article which compared the speed for list creation using 3 methods, viz, list comprehension, append, pre-initialization.
https://levelup.gitconnected.com/faster-lists-in-python-4c4287502f0a
In an attempt to become a better programmer I want to be able to create a cleaner code and one of the things that looks "messy" on the way I currently code is how I manage lists.
Typically I will (in the beginning of the code) start by defining the lists like this (below are completely arbitrary values I set into the lists) and then i iterate the proces many times throughout loops:
for i in range(100):
value1 = []
datapre = []
datapost = []
value1.append('Name')
value1.append('Number')
datapre.append(13)
dapre.append(16)
datapost.append(25)
datapost.append(28)
The above example only has 3 lists, however some times I need to use many different lists (like 50), which makes the code quite long, and I expect that good programmers do not actually work like this. So can anyone provides some tips on how you actually should store data?
The initialize-append way:
my_list = []
for i in range(10):
my_list.append(i**2)
The list-comprehension way:
my_list = [i**2 for i in range(10)]
What you choose to use depends on many factors, the most important of which (imo) is what else is done with it apart from populating the list. If they have to used elsewhere too, a for loop is advised to avoid re-iterating.
Then again, lists might not be the best choice in terms of data-structure for your specific problem, but that is impossible to judge from the info you provide.
I have a need to iterate over bunch of objects(30+ Objects are for 30+ buttons). Therefore I have a list looks like this,
myObjList = [my.obj.obj1, my.obj.obj2, my.obj.obj3, ....... ]
What would be the most elegant way to load a list with these objects?
Since you're looking for flexible dot access, you're probably best off with getattr in a list comprehension:
myObjList = [getattr(my.obj, 'obj'+str(i)) for i in range(n)]
where n is the number of obj<i> you need to get from my.obj.
I have a nested dictionary in Python. I can access the A element like this:
D[0]['detLog'][n]['A']
where n is from 0 to the length of the detLog... In Matlab I could use something like this:
D[0]['detLog'][:]['A']
: meaning "for all elements".
Is there something similar in Python?
Yes, use a list comprehension:
[d['A'] for d in D[0]['detLog']]
For scientific computing with Python, you may also want to look into NumPy and SciPy, specifically the NumPy for Matlab users documentation.
I think you want this, though it isn't so pretty:
[x['A'] for x in D[0]['detLog'].itervalues() if 'A' in x]
What we're doing is extracting the 'A' value from each dict if it exists, otherwise adding nothing to the result.