Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
xPanda
Feb 6, 2003

Was that me or the door?

deimos posted:

Are you using IPython yet? You should.

Yep, use IPython and you'll never want to use another interpreter again. Then you can start using IPython notebooks for mucking around with protocols and matplotlib chart generation and you'll wonder how you ever got by without it. I use them all the time for number crunching and analysis visualisation.

Adbot
ADBOT LOVES YOU

the
Jul 18, 2004

by Cowcaster

Ridgely_Fan posted:

If you're using Ubuntu you should use apt-get to install python packages (or the graphical thing, Synaptic I believe).

sudo apt-get install idle python-matplotlib

That should pull in numpy, scipy, and the pylab libraries. You might want to think about ipython as well (it's a nice shell for interactive python sessions).

Strange.

For some reason, it said that all of these modules were installed already.

However, earlier today I was getting error messages that they weren't installed, and I gave up.

Regardless, I'll donate to Red Cross for you.

Emacs Headroom
Aug 2, 2003
In terminal type 'which python'

It should say '/usr/bin/python'

It could have been that you manually installed a different python somewhere locally when you were trying to get things set up, and you were running that instead of the system python which should have the libraries installed.

the
Jul 18, 2004

by Cowcaster

Ridgely_Fan posted:

In terminal type 'which python'

It should say '/usr/bin/python'

It could have been that you manually installed a different python somewhere locally when you were trying to get things set up, and you were running that instead of the system python which should have the libraries installed.

I'm pretty sure that's the case. I had unpacked that .sh file, and I had also done an "apt-get install" for the packages, because I had no idea what I was doing.

How do I go about removing one of them?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Sinestro posted:

Even better, use OS X and you can have both!

It seems like 90% of the python package management problems in this thread are OS X-related.

OnceIWasAnOstrich
Jul 22, 2006

Sinestro posted:

With pythonz and Homebrew, it is actually awesome. Fink/MacPorts are both huge clusterfucks, though.

Homebrew is great when you have a recipe, which happens, sometimes. I hadn't heard of pythonz so I'll have to see how that works.

Thermopyle posted:

It seems like 90% of the python package management problems in this thread are OS X-related.

OSX is a mess because its enough like other actual unix systems that people don't generally go out of their way to make things work well with it, but it doesn't have all of the nice automatic package management of a BSD/Linux, so you either have to use broken package managers or do everything manually (or Homebrew, which does things manually...for you) Its really a terrible experience for people new to Python compared to Linux where things work great, or even Windows, where things are a pain in the rear end but either there is no support or you just install and go. It doesn't help that most people using OSX don't have the understanding of the unix underneath and expect Python to work as simply as everything on user-OSX.

That said, if you already understand how to manage Python and don't mind compiling everything yourself, OSX is amazing for it.

OnceIWasAnOstrich fucked around with this message at 01:53 on Jun 8, 2012

Emacs Headroom
Aug 2, 2003

the posted:

I'm pretty sure that's the case. I had unpacked that .sh file, and I had also done an "apt-get install" for the packages, because I had no idea what I was doing.

How do I go about removing one of them?

You should remove the one you manually installed. First, find out what python you're using: post the output of the command 'which python'. If it's /usr/bin/python, then you should be running off the system python, and you should be able to import the packages you've installed like scipy (and basically you don't have to worry about the other version if it's even there). If it's /opt/local/bin/python or /usr/local/bin/python or something like that, then you can change your PATH variable so that /usr/bin comes first, or you can manually delete that python (or delete it with the uninstaller that came with your shell script if there is one), or you could just rename the thing to something like /opt/local/bin/python-enthought.

I'm going to sleep early, so if you're still having trouble and others in the thread can't help I'll give you a hand tomorrow morning.

Comrade Gritty
Sep 19, 2011

This Machine Kills Fascists

OnceIWasAnOstrich posted:

Homebrew is great when you have a recipe, which happens, sometimes. I hadn't heard of pythonz so I'll have to see how that works.


OSX is a mess because its enough like other actual unix systems that people don't generally go out of their way to make things work well with it, but it doesn't have all of the nice automatic package management of a BSD/Linux, so you either have to use broken package managers or do everything manually (or Homebrew, which does things manually...for you) Its really a terrible experience for people new to Python compared to Linux where things work great, or even Windows, where things are a pain in the rear end but either there is no support or you just install and go. It doesn't help that most people using OSX don't have the understanding of the unix underneath and expect Python to work as simply as everything on user-OSX.

That said, if you already understand how to manage Python and don't mind compiling everything yourself, OSX is amazing for it.

I've not found homebrew python any harder to manage than Python on any of the Linux Distributions i've used.

Nippashish
Nov 2, 2005

Let me see you dance!

the posted:

Strange.

For some reason, it said that all of these modules were installed already.

However, earlier today I was getting error messages that they weren't installed, and I gave up.

Enthought exists separately from your system python, packages that are installed with apt-get won't be seen by Enthought.

Replacing your system python with Enthought is a bad idea (things will break), you need to keep them separate.

If you can get everything you need through apt-get then it's easier to stick with that method. If you want the features of Enthought (mainly fast linear algebra in numpy) then setting up Enthought may be worth it to you.

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES

BigRedDot posted:

Did you update your PATH and PYTHONPATH? EPD installs in a subdir in whatever random place you run the script. Did you try just "ipython --pylab" or even just "from pylab import *" ?

And IDLE... why on earth?

To be fair, I used IDLE for literally *all* the coding I did in grad school. I only recently permanently switched to using ipython and aquamacs.

I was almost completely new to vigorous coding before then. I had done shell scripting, a little perl (in emacs) and IDL ( :suicide: ), but my python experience was my first *real* attempt to learn a language. My first experiences were on IDLE in windows and Stani's Python Editor (which is actually nice too).

One thing I liked about IDLE is that it just seemed more intuitive. I admit, now that I switched it ipython, I'm annoyed at myself that I resisted it for so long. However, I'm a *lot* more comfortable with using the terminal than I was when I first started.

Given how much trouble he is having, I don't blame him for using IDLE. A lot of linux stuff really does seem frustrating to me, even now. I've been having to source install all my poo poo for well over 10 years, and I still want to throw poo poo out the window when *everything* breaks when I change a compiler from 10.5.3.1.3 to 10.5.3.1.4.

I understand *why* it happens, but at times it seems like maintaining a linux system (or installing everything from source in OSX) is like an MMORPG. Oh, you want this? Well, you need this, which just happens to require the jade monkey and three other quests. Enjoy losing an entire day! :)

OnceIWasAnOstrich posted:

Oh god Python on OSX. I develop on a Mac Pro, and I was initially in love with it. That was until I actually started using a package manager. You get to choose fink or macports, and you better hope everything you want is on one of those, because god forbid you try to mix compiled programs with fink/port installed dependences or the other way around, much less between the two.

It also seems like every third library I try to install is just completely broken on 10.7, and requires me to either patch it myself or badger the developers into fixing it.

Using Python on OSX is a nightmare with package managers. Everything is beautiful if I download binaries or compile everything myself (except for the fact that you have to fight with the default system installed Python sometimes). I'm experimenting with using a Linux VM and just running everything in that either with ssh or PyCharm remote interpreters.

Exactly. I literally broke my entire system trying to using macports (gently caress macports forever). Why? Well, because I loving decided to install gfortran myself and that means I should burn in hellfire for all eternity.

This is why I just install everything myself now, and stop using package managers.

the posted:

I'm using IDLE, because, well, that's the first thing I used when I started on my Windows desktop so I'm used to it.

I'm doing physics programming, so I just need a GUI where I can code small programs that use Pylab/matplotlib/scipy/numpy. That's about it.

I'm a physicist too, what do you work on?

Also, :hfive:. Also, download pyfits if you *ever* deal with fits files. You can get it from space telescope.

JetsGuy
Sep 17, 2003

science + hockey
=
LASER SKATES
Pyfits is a siren, listen to her alluring song and head for the rocks of never having to use loving CFITSIO ever again!
http://www.stsci.edu/institute/software_hardware/pyfits/Download

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Am I nuts or shouldn't this work:
Python code:
#snip
    for i, x in enumerate(input):
      stack.append((input[:i], state, x))
      state = self.next_state(state, x)
      if not state: break
    else:
      stack.append((input[:i+1], state, None))
#snip
pre:
    105       if not state: break
    106     else:
--> 107       stack.append((input[:i+1], state, None))

UnboundLocalError: local variable 'i' referenced before assignment
It runs fine if I put i = 0 above the loop, but why should I have to?

Python code:
In [4]: for i in range(10):
   ...:     pass
   ...: else:
   ...:     print i
   ...:
9
What am I missing?

Opinion Haver
Apr 9, 2007

You need to indent your else so that it lines up with the if (and then indent the thing below it so it's indented relative to the else). Right now the else is getting parsed as part of a 'for-else' block; the else statement executes after the for statement as long as it didn't break out. This is weird and I'm not sure why it's in the language, but there you go.

leterip
Aug 25, 2004

Munkeymon posted:

What am I missing?

If your input has no elements, i is never created.

Python code:
>>> def foo():
...     for i in []:
...             pass
...     else:
...             print i
... 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in foo
UnboundLocalError: local variable 'i' referenced before assignment

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



leterip posted:

If your input has no elements, i is never created.

Python code:
>>> def foo():
...     for i in []:
...             pass
...     else:
...             print i
... 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in foo
UnboundLocalError: local variable 'i' referenced before assignment

:doh: Didn't think it was getting called with empty input. Stupid assumption on my part.

yaoi prophet the for-else was intentional.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
Reading about strings and their literals at the moment. Is there a reason why in raw strings, the backslash escapes the string quote character, while being preserved in the string even when used in that way? It seems baffling. I realise that raw strings are just a convenience for more easily expressing some string literals and that there are plenty of ways around it.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Because it's hard to do in the lexer otherwise, and because there's otherwise no way to insert a regular quote character.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Suspicious Dish posted:

Because it's hard to do in the lexer otherwise, and because there's otherwise no way to insert a regular quote character.

How is it "hard to do in the lexer"? Seems like the lexer is already able to do comparable things when parsing regular string literals.

And I'm not disputing that there would be no way of inserting a regular quote character if they couldn't be escaped - I'm saying I don't understand the reasoning behind the backslash used to do the escaping being preserved in the resulting string.

Clugg
Apr 21, 2005

OK, so I have a question about python scripts on websites.

I'm a complete newbie to Python, web development and programming in general, but I basically just want to start out with a simple form which takes input, does something to it (with Python) and prints it on a line below the form.

I have my python module complete with function which does something to a string and then returns output.

So far, I have the following python script hosted on the site:

/cgi-bin/thing.py?input=something

This takes the input, calls mymodule.myfunction(input) and prints the output as a single line on an otherwise bare page.

What's the best thing to do from here? Would it be best to render a form using thing.py which refers to itself, or is there a way I can somehow call thing.py with a form and print its output on some other page?

Clugg fucked around with this message at 09:41 on Jun 10, 2012

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
You can return a 303 to redirect to another page.

Clugg
Apr 21, 2005

Suspicious Dish posted:

You can return a 303 to redirect to another page.

All good, I used print to render everything using the script and the form links back to the page.

I don't fully understand how python uses the print function to render the webpage though (cgi-bin) -- are there any resources that can explain this in detail?

Perhaps I'm just being dense, but it's not obvious to me. My first attempt literally just printed all the html code to the user as if all the HTML tags had been escaped.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
CGI basically takes what's on stdout and returns it as an HTTP request.

The 'escaped html tags' means that you didn't supply a correct mime type. You need to supply text/html, not text/plain, which is the default that CGI will send if you don't send a Content-Type header.

Clugg
Apr 21, 2005

Suspicious Dish posted:

CGI basically takes what's on stdout and returns it as an HTTP request.

The 'escaped html tags' means that you didn't supply a correct mime type. You need to supply text/html, not text/plain, which is the default that CGI will send if you don't send a Content-Type header.

Awesome. Thanks! That's probably all I need to go on for now.

Baby Nanny
Jan 4, 2007
ftw m8.

Clugg posted:

Awesome. Thanks! That's probably all I need to go on for now.

Not sure how far you want to take your python web development learning but CGI is pretty old and you should check out some of pythons great website making solutions that are out there. There's stuff like flask (http://flask.pocoo.org/) out there and of course django (http://djangoproject.org) also check out weurkzeug (I probably did not spell that right) which flask is based off of. Bottlepy is also great and is a one file dependency you can just drop in anywhere. Learning via writing cgi scripts probably wont be the most fun thing after you hit a certain point. Django also has the added benefit of having a great tutorial that is also a good intro into some basic python things.

There's also pyramid and a bunch of others I probably missed but the usual consensus when learning to make websites with python is to start with something like flask or django and go from there.

Red Mike
Jul 11, 2011

Baby Nanny posted:

Not sure how far you want to take your python web development learning but CGI is pretty old and you should check out some of pythons great website making solutions that are out there. There's stuff like flask (http://flask.pocoo.org/) out there and of course django (http://djangoproject.org) also check out weurkzeug (I probably did not spell that right) which flask is based off of. Bottlepy is also great and is a one file dependency you can just drop in anywhere. Learning via writing cgi scripts probably wont be the most fun thing after you hit a certain point. Django also has the added benefit of having a great tutorial that is also a good intro into some basic python things.

There's also pyramid and a bunch of others I probably missed but the usual consensus when learning to make websites with python is to start with something like flask or django and go from there.

To add to this, have a pretty good FAQ about Python webdev.

Stabby McDamage
Dec 11, 2005

Doctor Rope
I've been thinking about the fixed-point dollar representation question from earlier. Is there any more elegant way to implement fixed-point integer-based math than the below?

(besides using an existing library, of course)

Python code:
import operator,numbers
# US dollar class based on fixed-point integer math
# inherits the abstract Rational class to ensure all appropriate operators are implemented
class USD(numbers.Real):
    # instantiate a new dollar value.  accepts float or integer dollars if cents==False, float or integer cents if cents==True.
    def __init__(self, v, cents=False):
        self.v = v if cents else v*100
    
    # printing the object prints a formatted dollar value
    def __repr__(self): return "$%.2f" % (self.v/100.0)
    __str__=__repr__
    
    # indirect call for any binary operator
    def _binary_op(self, other, op, like_type_only=False, reverse=False):
        if reverse: 
            op_orig = op
            op = lambda a,b: op_orig(b,a)
        if isinstance(other, type(self)):
            return USD(op(self.v, other.v), True)
        elif not like_type_only and isinstance(other, numbers.Real):
            return USD(op(self.v, other), True)
        else:
            raise TypeError("Unable to '%s' %s and %s" % (op.__name__, type(self), type(other)))
    
    # indirect call for any unary operator
    def _unary_op(self, op): return USD(op(self.v), True)
    
    # binary operators which must be applied to other USD objects (e.g., we're disallowing USD+int since it's not clear if it's cents or dollars)
    def __add__(self,other):  return self._binary_op(other, operator.__add__, like_type_only=True)
    def __sub__(self,other):  return self._binary_op(other, operator.__sub__, like_type_only=True)
    def __eq__(self,other):   return self._binary_op(other, operator.__eq__,  like_type_only=True)
    def __le__(self,other):   return self._binary_op(other, operator.__le__,  like_type_only=True)
    def __lt__(self,other):   return self._binary_op(other, operator.__lt__,  like_type_only=True)
    def __radd__(self,other): return self._binary_op(other, operator.__add__, like_type_only=True, reverse=True)
    
    # binary operators applicable to any number
    def __div__(self,other):       return self._binary_op(other, operator.__div__)
    def __floordiv__(self,other):  return self._binary_op(other, operator.__floordiv__)
    def __mod__(self,other):       return self._binary_op(other, operator.__mod__)
    def __mul__(self,other):       return self._binary_op(other, operator.__mul__)
    def __pow__(self,other):       return self._binary_op(other, operator.__pow__)
    def __truediv__(self,other):   return self._binary_op(other, operator.__truediv__)
    def __rdiv__(self,other):      return self._binary_op(other, operator.__div__,      reverse=True)
    def __rfloordiv__(self,other): return self._binary_op(other, operator.__floordiv__, reverse=True)
    def __rmod__(self,other):      return self._binary_op(other, operator.__mod__,      reverse=True)
    def __rmul__(self,other):      return self._binary_op(other, operator.__mul__,      reverse=True)
    def __rpow__(self,other):      return self._binary_op(other, operator.__pow__,      reverse=True)
    def __rtruediv__(self,other):  return self._binary_op(other, operator.__truediv__,  reverse=True)
    
    # unary operators
    def __abs__(self): return self._unary_op(operator.__abs__)
    def __neg__(self): return self._unary_op(operator.__neg__)
    def __pos__(self): return self._unary_op(operator.__pos__)
    def __float__(self): return self._unary_op(operator.__float__)
    def __trunc__(self): return self.v  # the only "special" unary operator
    
    # money math
    def dollars(self): return int(self.v / 100)
    def cents(self): return int(self.v % 100)
Example usage:
Python code:
>>> x=USD(5)
>>> x
$5.00
>>> x+5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 26, in __add__
  File "<stdin>", line 20, in _binary_op
TypeError: Unable to '__add__' <class '__main__.USD'> and <type 'int'>
>>> x+USD(3)
$8.00
>>> x/3
$1.66

Stabby McDamage fucked around with this message at 19:46 on Jun 10, 2012

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Don't use integers.

Python code:
from decimal import Decimal

Stabby McDamage
Dec 11, 2005

Doctor Rope

Suspicious Dish posted:

Don't use integers.

Python code:
from decimal import Decimal

I read that page and I guess I don't fully understand. How are these Decimal values stored internally? Literally in base 10?

EDIT: Also, leaving the math aside, is there a better/shorter way to implement any pseudo-number? I was surprised to have to explicitly implement all the operators instead of just subclassing int (which didn't work, because the result of two subclassed ints added together is of type int, not the subclass).

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Stabby McDamage posted:

I read that page and I guess I don't fully understand. How are these Decimal values stored internally? Literally in base 10?

As a sign part, an integer part (also called the mantissa or coefficient) and an exponent part, as specified by IEEE754.

Sinestro
Oct 31, 2010

The perfect day needs the perfect set of wheels.

Suspicious Dish posted:

As a sign part, an integer part (also called the mantissa or coefficient) and an exponent part, as specified by IEEE754.

No, that is a float, not a Decimal. A Decimal is stored as a few strings.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Sinestro posted:

No, that is a float, not a Decimal. A Decimal is stored as a few strings.

No. You can look at the implementation, too. They have an integer component (d._int, technically stored as strings, but that's just an implementation detail to speed up conversion to/from strings, the most common case), and an exponent (d._exp):

Python code:
>>> from decimal import Decimal
>>> pi = Decimal("3.14") # good enough for nasa
>>> pi._int, pi._exp
('314', -2)

Stabby McDamage
Dec 11, 2005

Doctor Rope
I think we're all right at the same time.

Stabby McDamage posted:

Literally in base 10?

Suspicious Dish posted:

As a sign part, an integer part (also called the mantissa or coefficient) and an exponent part, as specified by IEEE754.

Sinestro posted:

A Decimal is stored as a few strings.

Yup, it's a base 10 string with exponent stored separately. Very cool.

When I first read the Decimal doc, I thought it was a IEEE754 floating point wrapper, but I was wrong...dead wrong. :c00l:

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Stabby McDamage posted:

When I first read the Decimal doc, I thought it was a IEEE754 floating point wrapper, but I was wrong...dead wrong. :c00l:

It is. IEEE754 has formats for binary and decimal floating points.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

Hammerite posted:

Reading about strings and their literals at the moment. Is there a reason why in raw strings, the backslash escapes the string quote character, while being preserved in the string even when used in that way? It seems baffling. I realise that raw strings are just a convenience for more easily expressing some string literals and that there are plenty of ways around it.
The point of raw strings is to avoid having to escape the backslashes, so anything which makes it so that you'd have to escape a backslash is obviously flawed. Ideally quotes would be escaped by doubling them rather than backslashes, but that could be difficult to parse as "a""b" is already valid and has a different meaning.

Hubis
May 18, 2003

Boy, I wish we had one of those doomsday machines...

Hubis posted:

I have a set of data representing a probability distribution function stored as an array of arrays. I'd like to compute the cumulative distribution function (i.e. the sum of each element and all those proceeding it) for each row (and then another CDF of each row's total). Is there a clever way to do this using list comprehensions? Right now I've got

code:
pdf = get_data()
cdf = pdf
for row in range(0, len(pdf)):
  for col in range(1, len(pdf[r]):
    pdf[row][col] = pdf[row][col] + pdf[row][col-1]
which seems a bit clunky.

in case anyone was curious,

code:
cdf = [sum(pdf[0:n]) for n in range(pdf)]
works pretty well. Modify for a 2D PDF as needed.

duck monster
Dec 15, 2004

Anyone had any luck getting libtcod working on a mac. It seems like a phenomenal library, but the lake of Makefiles, setup.py's or any sort of install instructions (the download on the site of the prebuilt doesnt include the all important python wrappers :( ) makes it a total headfuck.

I've had no joy at all :(

Clugg
Apr 21, 2005

Baby Nanny posted:

Not sure how far you want to take your python web development learning but CGI is pretty old and you should check out some of pythons great website making solutions that are out there. There's stuff like flask (http://flask.pocoo.org/) out there and of course django (http://djangoproject.org) also check out weurkzeug (I probably did not spell that right) which flask is based off of. Bottlepy is also great and is a one file dependency you can just drop in anywhere. Learning via writing cgi scripts probably wont be the most fun thing after you hit a certain point. Django also has the added benefit of having a great tutorial that is also a good intro into some basic python things.

There's also pyramid and a bunch of others I probably missed but the usual consensus when learning to make websites with python is to start with something like flask or django and go from there.



Thanks for the info. I had read that CGI is pretty old, but I just wanted to make a quick hack with CGI and try to make it work (and I happened to have a Linux VM with Apache installed).

Once I'm more familiar with Python I'm going to try out Flask/Django.

davebees
Feb 18, 2009
I'm a Mathematica guy just starting to learn Python. In Mathematica, you can input something like:
code:
 {1,2,3} * 2 
and get
code:
 {2,4,6} 
Is there any convenient way to do stuff like this in Python? The best I can come up with right now is this convoluted thing:
code:
 map(lambda x: x*2, [1,2,3]) 

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

Starno posted:

I'm a Mathematica guy just starting to learn Python. In Mathematica, you can input something like:
code:
 {1,2,3} * 2 
and get
code:
 {2,4,6} 
Is there any convenient way to do stuff like this in Python? The best I can come up with right now is this convoluted thing:
code:
 map(lambda x: x*2, [1,2,3]) 

  1. List comprehensions are a bit nicer/easier to understand:
    code:
    In [1]: [x * 2 for x in [1, 2, 3]]
    Out[1]: [2, 4, 6]
    
  2. Use NumPy:
    code:
    In [1]: import numpy as np
    
    In [2]: a = np.array([1, 2, 3])
    
    In [3]: a * 2
    Out[3]: array([2, 4, 6])
    

Adbot
ADBOT LOVES YOU

davebees
Feb 18, 2009

Oh this looks great. Thanks!

  • Locked thread