Here's the code:
import datetime
local = {};
class name:
x = 0
y = 0
time = 0
PCH = []
FCC_Queue = []
t = datetime.time(0, 0, 0)
p = name()
p.x = 10
p.y = 20.0
p.time = t.second
PCH.append('xyz','abc',1,15.0)
FCC_Queue.append(10.0,20.0,30.0)
local['Obj1'] = p
How do I access the value of p.x from the dict local['Obj1']?
Also, how do I access a list value e.g. PCH[1] from the dict local['Obj1']?
Of course you can and your code works.
To access the x of your object is as simple as
localhostrecord['Obje1'].x
To access the list you do the same and then treat this as a simple list
localhostrecord['Obje1'].PCH
# e.g. access second element of PCH list
localhostrecord['Obje1'].PCH[1]
Related
def bulk_save_coordinates():
index = 0
coordinates_list = []
for element in range(count_indexes()):
coordinates = Coordinates(latitude=all_location_coordinates[index], location_id=index + 1, longitude=all_location_coordinates[index])
coordinates_list.append(coordinates)
index += 1
session.add_all(coordinates_list)
session.commit()
def bulk_save_timezones():
index = 0
timezones_list = []
for element in range(count_indexes()):
timezones = Timezone(offset=all_location_coordinates[index], location_id=index + 1, description=all_location_coordinates[index])
timezones_list.append(timezones)
index += 1
session.add_all(timezones_list)
session.commit()
That is my function. I need to use bulk_save_something a lot.
I see that the logic repeats itself there, it is the same pattern. I would like to put in function args something that will not be a string.
Maybe someone have an idea how to change that?
You can create a more generic function by sending the changing parameter (here the Coordinates/Timezone class ?)
def bulk_save(obj_class):
index = 0
obj_list = []
for element in range(count_indexes()):
objs = obj_class(offset=all_location_coordinates[index], location_id=index + 1, description=all_location_coordinates[index])
obj_list.append(objs)
index += 1
session.add_all(obj_list)
session.commit()
a1 = 0
a2 = 1
x = [] #here I have declared an empty list
for i in range(2):
x.append('a'+str(i+1)) #to append the variable with a numbering scheme
print (x)
This is a sample python code. A similar situation that I am facing in a programming task .
Here the output is ['a1','a2'] instead I need the output as [0,1]. Can someone help me with this ?
Use a dictionary for this:
d = {'a1': 0, 'a2':1}
x = [] #here I have declared an empty list
for i in range(2):
x.append(d['a'+str(i+1)]) #to append the variable with a numbering scheme
print (x)
If you MUST use variables already existing in your scope, you can use locals() to get all local variables as a dict
a1 = 0
a2 = 1
x = [] #here I have declared an empty list
for i in range(2):
x.append(locals()['a'+str(i+1)]) #to append the variable with a numbering scheme
print (x)
vars = {
'a1': 0,
'a2': 1,
}
x = []
for var in vars.keys():
x.append(vars[var])
print(x)
I am trying to build a list in Python as below. I want to call this function multiple times and build a json array, when i try with json.dumps for p in range (0,10) it adds extra [] for each json object
def buildlist():
objects_list = []
d = collections.OrderedDict()
d['batteryLevel'] = random.randint(0, 100)
d['firmwareVersion'] = "2016-04-16-ENGG"
d['macId'] = MACprettyprint(randomMAC())
d['name'] = "".join([random.choice(string.digits+string.letters) for i in xrange(7)])
d['rssi'] = random.randint(0, 100) * -1
d['status'] = random.choice([OPEN, LOCKED])
objects_list.append(d)
return objects_list
I'm not exactly sure what your question is. But the function you posted will always return a list containing just a single OrderedDict. Why don't you just return the OrderedDict and build the list outside the function?
def builditem():
d = collections.OrderedDict()
d['batteryLevel'] = random.randint(0, 100)
...
d['status'] = random.choice([OPEN, LOCKED])
return d
json.dumps([builditem() for n in range(10)])
I am writing a piece of code that takes an input that varies according to discrete time steps. For each time step, I get a new value for the input.
How can I store each value as a list?
Here's an example:
"""when t = 0, d = a
when t = 1, d = b
when t = 2, d = c"""
n = []
n.append(d) #d is the changing variable
for i in range(t):
n.append(d)
What I expect to get is:
for t = 0, n = [a]; for t = 1, n = [a,b]; and for t = 2, n = [a,b,c]
What I actually get is:
for t = 0, n = [a], for t = 1, n = [b,b]; and for t = 2, n = [c,c,c]
See comment below, but based on the additional info you've provided, replace this:
n.append(d)
with this:
n.append(d[:])
Which type is the variable 'd'? If it is, for instance a list, the code you are showing pushes onto tbe list 'n' a reference to the variable 'd' rather than a copy of it. Thus, for each iteration of the loop you add a new reference of 'd' (like a pointer in C) to 'n', and when 'd' is updated all the entries in 'n' have, of course, the same value
To fix it you can modify the code so as to append a copy of 'd', either:
n.append(d[:])
n.append(list(d))
n.append(tuple(d))
You can simply do this
n = []
for i in range(t + 1):
n.append(chr(i+ord('a'))
And if you do not want to store the characters in the list rather some specific values which are related with d, then you have to change d in the for loop
n = []
d = 1
for i in range(t + 1):
n.append(d)
d += 2
It is difficult to say without seeing the code. But if d is not an int, this could happen. If d is a list for instance, it is passed by reference
n = []
d = [1]
n.append(d)
d[0] = 2
n.append(d)
print(n)
>>>> [[2], [2]]
So if each new d is just modified, your probleme arise. You can solve it by copying d :
from copy import copy
n = []
d = [1]
n.append(copy(d))
d[0] = 2
n.append(copy(d))
print(n)
>>>> [[1], [2]]
If you just wrap the variable inside an object you can watch what is being set to the variable by overriding __setattr__ method. A simple example.
class DummyClass(object):
def __init__(self, x):
self.history_of_x=[]
self.x = x
self._locked = True
def __setattr__(self, name, value):
self.__dict__[name] = value
if name == "x":
self.history_of_x.append(value)
d = DummyClass(4)
d.x=0
d.x=2
d.x=3
d.x=45
print d.history_of_x
Output :-
[4, 0, 2, 3, 45]
I am using liblas in Python to read, manipulate and write a special point format *.las. I have a string as
s = "309437.95 6959999.84 118.98 16 1 1 0 0 1 0 112.992 5.9881"
Where the first is the X, the second the Y, the third element the Z etc.
Using Liblas, I create an empty liblas.point.Point object
>>> pt = liblas.point.Point()
>>> pt
<liblas.point.Point object at 0x0000000005194470>
After that I need to fill this object because is empty.
>>> pt.x, pt.y,pt.z
(0.0, 0.0, 0.0)
probably using
>>> pt.get_x
<bound method Point.get_x of <liblas.point.Point object at 0x0000000005194470>>
I wish to say thanks for all help and suggestion, I really need to solve this step.
from suggestion of Martijn Pieters
s = "%s %s %s" % (s, value, nh)
>>> s
'309437.95 6959999.84 118.98 16 1 1 0 0 1 0 112.992 5.9881'
# create a liblas.point.Point
pt = liblas.point.Point()
pt.x = float(s.split()[0])
pt.y = float(s.split()[1])
pt.z = = float(s.split()[11]) # the new Z value
pt.intensity = = int(s.split()[3])
pt.return_number= int(s.split()[4])
pt.number_of_returns = int(s.split()[5])
pt.scan_direction = int(s.split()[6])
pt.flightline_edge = int(s.split()[7])
pt.classification = int(s.split()[8])
pt.scan_angle = int(s.split()[9])
There are raw_x, raw_y and raw_z properties on a Point object; simply set those:
pt.raw_x = 309437.95
pt.raw_y = 6959999.84
pt.raw_z = 118.98
There are also x, y and z properties; it is not immediately clear from the source code what the difference is between the two types:
pt.x = 309437.95
pt.y = 6959999.84
pt.z = 118.98
but the library can produce these objects directly from a .las file for you, can't it? The File class you had trouble with before certainly does return these objects already.
And since you updated to show some code, here is a more readable version of that:
pt = liblas.point.Point()
s = map(float, s.split())
pt.x, pt.y, pt.z = s[0], s[1], s[11]
pt.intensity, pt.return_number = s[3], s[4]
pt.number_of_returns, pt.scan_direction = s[5], s[6]
pt.flightline_edge, pt.classification = s[7], s[8]
pt.scan_angle = s[9]