Member Avatar

Hi guys, This feels like something that should be possible in Python, and something that I feel like I should know how to do. Image I have a list of numbers: items=[10,20,30] Let's say I wanted iterate over them and define two new variables, a and b. a=[] b=[] for item in items: a.append(item*10) b.append(item*20) I can also do this in two list comprehensions: a=[item*10 for item in items] b=[item*20 for item in items] It feel like I should be able to do this in one single expression. Something like: a,b=[(item*10),(item*20) for item in items] Is this possible? Thanks.

Member Avatar
0
3
Member Avatar

Hi guys, I am running a costly simulation and trying to optimize the output. I'd have a fixed range over which the parameter of interest can vary, and about 100 values it can take in between. We know the result we are looking for and want to find the parameter value that comes closest to this. Instead of iterating the parameter incrementally, from say 0 to 100, I'd like to implement some sort of binary search algorithm. I am sure there is a "best" value on this range, so there's no need to worry about duplicate values. The algorithm in …

Member Avatar
0
4
Member Avatar

Hi guys, I've downloaded 2 cached_property implementations from the internet and both did not work correctly for my programs. Does anyone here used a cached_property function that works really well and could share with me?

Member Avatar
0
10
Member Avatar

Hi, I'm having some difficulty reading in boolean values from a file, particularly false values. Python can understand false values as empty strings, as well as a few other ways. For example: In [43]: bool(0) Out[43]: False In [44]: bool(False) Out[44]: False In [45]: bool('') Out[45]: False The problem is, anything I read in from a file is read in as a string. So if a file has these values, all the booleans will evaluate to true. For example: In [46]: bool('0') Out[46]: True In [47]: bool('False') Out[47]: True Therefore, in my file, I chose to use empty strings to …

Member Avatar
0
5
Member Avatar

Hi, I am trying to create the most general function possible to test if an object passed into it has mutability or not. With some prior help from pytony, it seemed that the best way to do this is to try to set and attribute. If the attribute can be set, it is mutable, otherwise it will force an error. To make this function general, I need to be able to pick an attribute from the object. I thought the best way to do this would be to list the attributes, pick the first one listed and then overwrite it. …

Member Avatar
0
12
Member Avatar

Hi, I'm curious about a few conventions. If you have a function that can return a or b based on some conditionals, which do you think is the best/accepted notation? def test(val): if val > 10: return a else: return b Or def test(val): if val>10: return a return b I often see both of these conventions used and wondered what you guys would recommend. Additionally, I commonly see these dual notations: if x==True: do stuff VS if x: do stuff Is there a preferred convention in this case? Thanks.

Member Avatar
0
3
Member Avatar

Hi, I have several functions that I'd like to operate on both mutable and immutable containers (mostly tuples vs. objects) and I'm looking for the optimal way to test for mutability in these objects. I can think of many ways to do this. For example: try setattr: do mutable stuff except Error: do immutable replacements I also considered adding a metaattribute to my classes based on mutability; however, this limits the usage of my functions to just the customized objects in my programs. I could also make 2 functions, one for mutable and one for immutable objects, but then I …

Member Avatar
0
3
Member Avatar

Hi, I have an object subclass that I am using with a cusom __repr__() method. class NewClass(object): def __repr__(self): return ', '.join('%s=%s'%(k, v) for (k,v) in self.__dict__.items()) This works fine (leaving out some more details about my program): test=NewClass(a=1,b=2) print test a=1, b=2 But what I really want for reasons that aren't really worth getting into is for the class name to be printed out in the __repr__ as well. For example, print test 'NewClass: a=1, b=2' But python objects don't have a __name__ attribute. I'd prefer not making a separate attribute, aka: class NewClass(object): name='NewClass' def __repr__(self): return name+', …

Member Avatar
0
3
Member Avatar

I have a simple class that stores attributes: In [1]: class Test(object): ...: a=10 ...: b=20 I have a function that returns attributes using attrgetter, and it accepts these through the args parameter to allow a user to pass various attribute fieldnames in. For example: In [4]: def getstuff(*args): ...: return attrgetter(args) I can manually pass multiple arguments to an attrgetter and return the attributes from my class: In [10]: f=attrgetter('a','b') In [11]: f(test) Out[11]: (10, 20) However, my getstuff function doesn't work because args is a list and attrgetter takes only comma separated strings: n [18]: f=getstuff('a','b') In [19]: …

Member Avatar
0
3
Member Avatar

Hi, I've been having trouble posting a code snipet tonight, I keep getting this error: The code snippet in your post is formatted incorrectly. Please use the Code button in the editor toolbar when posting whitespace-sensitive text or curly braces. My code is running fine in wingware IDE with 4 space margins everyhwere and no tabs. Perhaps someone who has posted snippets could take the code and description and post on my behalf? I wanet dot post for the contest but its really not important I suppose. If possible, respond here or pm me. Thanks.

Member Avatar
0
4
Member Avatar

I'd like to make a dictionary subclass that takes in positional keywords in addition to the standard *args, **kwargs. I found this example on stackoverflow: class attrdict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self a = attrdict(x=1, y=2) print a.x, a.y print a['x'] b.x, b.y = 1, 2 print b.x, b.y I'd like to know how to modfiy it to take in a positional argument. Something like: class attrdict(dict): def __init__(self,positional, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.positional=positional ### This doesn't a = attrdict(50, 30, 20) >>>TypeError: dict expected at most 1 arguments, got 2 This doesn't seem …

Member Avatar
0
3
Member Avatar

Hi, I think I have a pretty simple question but my google searches are giving me more information than I need. I think my terminology is not clear. Let's say I'm making a dictionary to hold a datatype very specific to some filetype or data of interest. Let's say I have the following data in a file: 'keith' 100, 50, 'puppy' 'bill' 300, 32, 'cat' This data is arbitrary, but I will create a dictionary keyed by the first column, and then the other entries will be stored in either a list or tuple. The first two entries of the …

Member Avatar
0
24
Member Avatar

Hi, I have been subclassing namedtuple to handle my custom data type: fields=['Query', 'u1', 'Accession] Old = namedtuple('Old', fields, verbose=False) class New(Old): def __repr__(self): return 'Overwriting works nicely' p=New('Hi',2,3) print p >>> 'Overwriting works nicely' What I want to do is to add the behavior that some of my fields must be a certain type. For example, 'Query' must be a string. If the user does something like: p.Query=50 I want it to raise an error. I tried overwriting the set_item attribute, but to no avail. Is there anyway to make the named tuple aware of what data type each …

Member Avatar
-1
2
Member Avatar

Hi guys, This is more a general discussion of methodology than a specific question. I have been working on a, the primary purpose of which is to store an oddly formatted data file (aka not you classic CSV). At the end of the day, the data is stored in a custom dictionary (thanks for help with this previously guys). In defining many of the methods, I realized that it's not always clear to me if I should write an instance method, or if I should write general methods and pass objects into them. def testmethod(self, args...) def testmethod(args...) There are …

Member Avatar
0
16
Member Avatar

Hi guys, I was working with the pandas package and was so impressed with how simple something was that I had to share. Have you ever worked with csv data (in excel for example) and wanted to import the data to python, take either a column average or row average, then plot it? For example, imagine I have data formatted like: file1 file2 file3 500 50.0 53.3 43.0 550 23.1 32.0 32.5 600 23.0 23.0 35.0 700 42.0 31.0 44.0 Pandas is a library for handling ordered series data and is GREAT for managing it. It essentially created containers that …

1
3
Member Avatar

Hi, If I have a list of strings, it's easy to output them using .join(). For example: mylist=['hi', 'there', 'girls'] myout='\t'.join(mylist) What I want to know is if there is a builtin python method that acts like join, except it automatically converts ints and floats to strings without giving a Type Error. For example, it would not error with this: mylist=['hi', 'there', 'girls', 5000] myout='\t'.join(mylist) TypeError: sequence item 1: expected string, int found I understand that I can simply fix mylist in one line with: `my_newlist=[str(entry) for entry in mylist]` However, this is such a common operation that I thought …

Member Avatar
0
7
Member Avatar

Real quick question. If I have a string 'hi my name is bill' and I want to reduce this to a list of letters, with no whitespaces (eg ['h', 'i', 'm', 'y'] as opposed to ['hi', 'i', ' ' , 'm', 'y', ' ', 'n'...]), is there a really quick and tidy way to do this? Or should I say, what is the best way? If I use: s='hi my name is bill' print list(s) Spaces are not removed. I've also thought to try: ls=[letter for letter in s.split() if letter != ' '] This doesn't work because first of …

Member Avatar
0
5
Member Avatar

Hey everyone, Last semester my buddy and I made a tutorial on application programming in Python. This video uses the Enthought Tool Suite (ETS), a free powerful Python development toolkit, to build quick, easy and powerful GUI's. I see many posts on this site about Tk, wx, qt but haven't seen much of anything about the ETS. I think that most users will be happily surprised at how easy it is to make graphical interfaces and event handlers using these tools. I would recommend this video to anyone who is not familiar with ETS and especially people who aren't highly …

Member Avatar
0
3
Member Avatar

Hey guys, I've looked over several Google results for basic explanations on [CODE]is / '=='[/CODE] However, I don't think I quite understand enough to know what is the ideal operator for this. [CODE]mylist=[1,2,3] if type(mylist) == list: print 'yes'[/CODE] or do I use [CODE] if type(mylise) is list: print 'yes'[/CODE] I understand superficially that == tests value and is test identifier (in the memory?) but not sure I really understand what is the best solution here. THanks

Member Avatar
0
7
Member Avatar

Hey guys, In prepping for a job interview, I'm trying to eliminate some bad habits and this trivial problem has me realizing how hard that is :'(. The problem: Print a 12 x 12 multiplication table. This is easy.... [CODE]outstring='' for i in range(1,13): for j in range(1,13): outstring +='\t'+str(i*j) #+= is add new value print '\n', outstring outstring='' [/CODE] Resulting in 1 2 3 4 5 6 7 8... 2 4 6 8 10 12 14 16... etc Ok no biggy, but what I want to do now is to get rid of my sloppy outstring method and use …

Member Avatar
0
14
Member Avatar

I've followed a tutorial where a Person class was used to illustrate the difference between class and instance variables. Something like: [CODE] class Person(object): population=0 def __init__(self, name): self.name=name Person.population += 1 print 'current population', Person.population Sally=Person('sally') Joe=Person('joe') [/CODE] This example really illustrated the difference between class and instance variables to me; however, it also really confuses me. When I think about it, the Person class is holding the attributes for an individual. The concept of a population; however, is a group of people. Therefore, it seems natural in OOP that a container class, "People" would store the variable population. …

Member Avatar
0
4
Member Avatar

Hey guys, I have a simple numpy datatype: [CODE]spec_dtype = np.dtype([ ('wavelength', float), ('intensity', float) ])[/CODE] I chose to use this in my program because it's very easy to read in 2-column spectral data files using the genfromtxt() method. Therefore, I made a fairly sizable program around this datatype. Now I'm running into a situation wherein I need to pass internal data lists for the "wavelength" and "intensity", rather them importing them externally from a file. This is giving me headaches with manual array creation. Imagine I have a list of wavelengths and intensity variables pre-stored in my program. For …

Member Avatar
0
3
Member Avatar

I have data which has a very particular format that I'm trying to store in a numpy array. avi_05MSalt00001.txt 2012 Feb 07 20:12:41 50000 (usec) 300 10 I've defined the following numpy datatype: [CODE]timefile_dtype=numpy.dtype([ ('filename', file), ('year', int), ('month', str), #Why don't these work? ('day', int), ('time', str), ('int_time', int), ('unit', str), ('avg', int), ('boxcar', int), ])[/CODE] The output looks like this:' ('avidin_in_water00349.txt', 2012, '', 29, '', 50000, '', 300, 10) Is it possible for numpy to store these string variables? If so, am I doing something wrong? I like the swiftness of this method rather than making my own …

Member Avatar
0
3
Member Avatar

Hey everyone, I have a set of classes which, when instantiated, take up a lot of memory. I'm trying to write a program which can inspect class attributes and methods given a list of classes, without actually instantiating them. Let's say I wanted to see if the following class had an attribute called "foo" [CODE] class Test(object): foo=str() bar=int() [/CODE] I know I can do something like: [CODE] test=Test() if test.f is not None: print 'found' [/CODE] However, is it possible to do this without instantiating Test? In reality, I need to do this with 10 objects, all of which …

Member Avatar
0
4
Member Avatar

Hey everyone, I've been using python quite a bit to develop scientific applications. As of late, the Enthought Tool Suite is proving to be one of the handiest set of development tools out there. One question I have is, with commercial software, I often see the ability to plugin output for a device. For example, my OceanOptics spectrometer comes bundled with software which allows real-time interaction with the experimental data. I would like to write program that have such functionality in python. I don't really understand; however, at what level one tends to begin including such additions (low-level vs. high-level). …

Member Avatar
0
3
Member Avatar

Hey everyone, this should be simple, but I keep running into errors so help is greatly appreciated. I have a large class, call it class A, which has several methods. Most of these methods modify data. [CODE]ClassA() def __init(X,Y,Z) ... .. def data_mod1(): ... def data_mod2(): ... [/CODE] I'm dealing with a large GUI program, which has several connected buttons. Therefore, I have another class to do nothing but handle button operations. Most of these operations are stylistic (changing colors and names). For example: [CODE]class Button_manager() def color_style1(): .... def attribute_style1(): .... [/CODE] Here is the issue. At some point, …

Member Avatar
0
8
Member Avatar

Hey everyone, I'm checking some bessel functions in python using mathematica, and I can't find anything online about how to import values into python with exponentials. I know how to values with exponents. For example: [CODE]x=2032.43 * 10 **23[/CODE] However, when I read in a data file, say with one column of values such as the one above, such a notation is not recognized by: [CODE]f=open('data.dat', 'r') for line in f: print float(line) [/CODE] I've also tried other notations. What is the correct notation? Thanks

Member Avatar
0
3
Member Avatar

Hey all, After beating my head against the wall with this, I decided to post. I'm using f2py, a wrapper to call Fortran routines from python. I can't use it because my current version of gcc does not support f2py. According to a posted solution, I have to edit my python Makefile such that: "edit the variable BASECFLAGS to exclude -Wno-long-double" . In the makefile, I've found the variable: [CODE]OPT= -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes BASECFLAGS= -fno-strict-aliasing CFLAGS= $(BASECFLAGS) $(OPT) $(EXTRA_CFLAGS)[/CODE] But have no damn idea how to exclude -wno-long-double. Any help would be so appreciated. But

Member Avatar
0
3
Member Avatar

Hey everyone, I've tried extensively to find a thread like this already, so I hope it's not a repose. Basically, I have a program with a nice GUI (Tkinter) which has a frame which takes in matplotlib figures. I am able to connect the plots to the Tkinter frame this way: [CODE] def graph_area(self, frame): '''Used to store parameters''' self.graphframe = Frame(frame) self.graphframe.pack(side = RIGHT) self.f = Figure(figsize=(5,4), dpi=100) self.ax1 = self.f.add_subplot(111) self.canvas = FigureCanvasTkAgg(self.f, self.graphframe) self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) [/CODE] This works very nicely; however, I would really like to have the flexibility to incorporate mlab plots into this frame …

Member Avatar
0
2
Member Avatar

Hey everyone, I'm making a data analysis suite in python, and want to construct a custom event handler which will reset the axis based on the data in the current subplot. To do so, I need the event handler to know what data is currently in the subplot. The matplotlib Axes and Axis classes are good at telling you the data limits in the entire plot, but not when the plot is zoomed in. So for example, if my data runs from -100,100 on the x-axis, and I zoom into a window of -50,50, I need a command that will …

Member Avatar
0
2

The End.