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
hey mom its 420
May 12, 2007

Doing stuff like that is generally not cool. You're using exec, polluting your global namespace, etc. I don't know what you ultimately achieve here since you only gave us a part of the code, but why not use a dict? A dict is used to map keys to values and it seems like that's what you're doing here.

So I'd prefer
code:
enums = {}
for i, id in enumerate(enumIDs):
  enums[id] = i
Or more tersely:
code:
import itertools
enums = dict(zip(enumIDs, itertools.count()))
And then you access it like so
code:
>>> enums['ID_NEWPROJECT']
0
Also, why are you storing numbers as strings? It's generally better to store them purely as numbers because if you need them in string form at some point, you can always just do str(x) later.

Adbot
ADBOT LOVES YOU

Moof Strydar
Jul 13, 2001

Sorry, should have provided more info. The vars are, for example, for use with wxPython, giving unique IDs to buttons and whatnot, and the wxPython functions require numbers.

I guess there was some misguided thought that it would be a bit more efficient using variables instead of a dict, though thinking about it now, aren't all variables actually just strings in the dict of a Python script? So that doesn't matter.

It does make the code fractionally more concise later on; you just have to type ID_NEWPROJECT instead of enums['ID_NEWPROJECT'], though if that's at the cost of using exec and polluting the namespace I guess it's not such a good tradeoff.

The other use I thought of was having an external script to your main one, which just stores the constants which you can then import individually. Possibly could do this by, I don't know, replacing the script's dict with a new one? That's probably a terrible idea.

I think you misunderstood the str(i) bit, that's just for use with exec, as it operates on a string; the vars end up being numbers once the exec statement is actually executed.

Anyway, you didn't answer my question. :colbert:

hey mom its 420
May 12, 2007

Ah, yeah, right, the str is for the exec.

Anyway, if all the data that goes into exec is from within your system, you're technically safe. In your case, it's right there in the same script, hardcoded by you, so it comes from within your system. If data you put in exec comes from some untrusted source (like the user), then it's a vulnerability.
The thing why it's bad to use exec generally is because you may one day decide that something that you hardcoded previously should come from the user and you may not notice that it later gets fed into exec.

Putting stuff like that into the global namespace is not considered good practice, since that can easily lead to name mix-ups and it's best to have everything in the smallest scope that you need. True, the namespace is represented as a dict, but it's important what's in which dict and it's nice to have stuff nicely scoped.

But if you really want to put those names in the global namespace, you could achieve the same functionality without using exec like so:
code:
for i, id in enumerate(enumIDs):
  globals()[id] = i
That would make it behave like the example you previously posted, only without the pesky exec.

duck monster
Dec 15, 2004

Lancer383 posted:

Not sure why you're having that issue with the print command -- have you tried using sys.stdout.write(string)? In your example it would be:

code:
import sys

name = raw_input("What is your name?")
sys.stdout.write(name + " is a stupid name.")

What would you gain from that?

Anyway. Try this;-

code:
import sys

name = raw_input("What is your name?").rstrip()
print name , " is a stupid name."
the .rstrip() strips the carriage return off the string before passing it into name.

oRenj9
Aug 3, 2004

Who loves oRenj soda?!?
College Slice

Moof Strydar posted:

The other use I thought of was having an external script to your main one, which just stores the constants which you can then import individually. Possibly could do this by, I don't know, replacing the script's dict with a new one? That's probably a terrible idea.

This should do what I think you're asking for:

events.py
code:
import wx

class events:
  FILE_NEW = wx.NewId()
  FILE_OPEN = wx.NewId()
  FILE_SAVE = wx.NewId()
main.py
code:
import wx
import events # Assuming events.py is in an included path.

file_menu = wx.Menu()
file_menu.Append(events.FILE_NEW, "&New", "Create new file on disk.")
file_menu.Append(events.FILE_OPEN, "&Open", "Open from file.")
file_menu.Append(events.FILE_SAVE, "&Save", "Save to a file.")

oRenj9 fucked around with this message at 16:11 on May 1, 2008

duck monster
Dec 15, 2004

Can someone fix that fugging faq.

Python was not designed as a teaching language. It was designed as a scripting language for Andrew Tannenbaum's Amoeba Operating system, which is where I first heard of it many many moons ago.

Zedlic
Mar 10, 2005

Ask me about being too much of a sperging idiot to understand what resisting arrest means.
I need to read a string containing ASCII control characters, but Python won't let me. Even if I read it as a raw string it says "SyntaxError: EOF while scanning triple-quoted string".

An example of a string is:
×J^@¯^@^@
^AQU TEXT
.TEXT TIMESTAMP
^BTEXT

Where ^@ is an ASCII NULL, ^A is start of heading and ^B is end of heading.

I'm sure there's an easy way around this but I can't find it. Any help appreciated.

No Safe Word
Feb 26, 2005

Zedlic posted:

I need to read a string containing ASCII control characters, but Python won't let me. Even if I read it as a raw string it says "SyntaxError: EOF while scanning triple-quoted string".

An example of a string is:
×J^@¯^@^@
^AQU TEXT
.TEXT TIMESTAMP
^BTEXT

Where ^@ is an ASCII NULL, ^A is start of heading and ^B is end of heading.

I'm sure there's an easy way around this but I can't find it. Any help appreciated.

Post the code. The error you've got sounds like not an error with your logic, but with your actual code (syntax :downs: ).

tef
May 30, 2004

-> some l-system crap ->

duck monster posted:

Python was not designed as a teaching language. It was designed as a scripting language for Andrew Tannenbaum's Amoeba Operating system, which is where I first heard of it many many moons ago.

It was 'heavily influenced' by ABC, a language designed for teaching.

quote:

In 1986 I moved to a different project at CWI, the Amoeba project. Amoeba was a distributed operating system. By the late 1980s we found we needed a scripting language. I had a large degree of freedom on that project to start my own mini project within the scope of what we were doing. I remembered all my experience and some of my frustration with ABC. I decided to try to design a simple scripting language that possessed some of ABC's better properties, but without its problems.

So I started typing. I created a simple virtual machine, a simple parser, and a simple runtime. I made my own version of the various ABC parts that I liked. I created a basic syntax, used indentation for statement grouping instead of curly braces or begin-end blocks, and developed a small number of powerful data types: a hash table (or dictionary, as we call it), a list, strings, and numbers.

I took ABC's ingredients and shuffled them around a bit. Python was similar to ABC in many ways, but there were also differences. Python's lists, dictionaries, basic statements and use of indentation differed from what ABC had. ABC used uppercase for keywords. I never got comfortable with the uppercase, neither reading nor typing it, so in Python keywords were lowercase.

I think my most innovative contribution to Python's success was making it easy to extend. That also came out of my frustration with ABC. ABC was a very monolithic design. There was a language design team, and they were God. They designed every language detail and there was no way to add to it. You could write your own programs, but you couldn't easily add low-level stuff.

[...]

I already knew we would want to use Python on different platforms. I knew we wanted to use Python on Amoeba, the operating system we were developing, and on UNIX, the operating system we were using on our desktops.

Although it was written as part of the ameoba project, it seems he was considering more general goals very early on.

leinad
Jan 14, 2003

Edit: Nevermind.

Instead, if someone wants to show me how to rewrite this in a more Python way, that would be cool. I'm sure it can be done in a single somehow.

code:
for k in range( 0, 5 ): 
  f = 1 
  for j in range( 0, 5 ): 
    if j != k: 
      f = f * ( - x[i[j]] * inverse( x[i[k]] - x[i[j]], p ) ) 
  M += y[i[k]]*f 

return M % p 

leinad fucked around with this message at 23:05 on May 6, 2008

karuna
Oct 3, 2006
Hey, how do you pass a variable within a URL?

I am using urllib2

code:
urllib2.urlopen('http://www.somewhere.com/some_other_crap<$MYVAR&>')
This isn't working for me at all, i have also tried %MYVAR and ("\<\$"+"MYVAR"+"\$\>")

Any help would be great, thanks

Also i'm having another problem..

I'm trying to generate a xml file.
I can generate an xml file, However the content is hardcoded in the python script.

like so
code:
 #create a <type> element
paragraph2 = xml.createElement("type")
maincard.appendChild(paragraph2)

#Give type text
typeText = xml.createTextNode("Show")
paragraph2.appendChild(typeText)
How should i go about getting the HTML that i scraped using BeauituflSoup from another script and generating an xml file from it?

No Safe Word
Feb 26, 2005

karuna posted:

Hey, how do you pass a variable within a URL?

I am using urllib2

code:
urllib2.urlopen('http://www.somewhere.com/some_other_crap<$MYVAR&>')
This isn't working for me at all, i have also tried %MYVAR and ("\<\$"+"MYVAR"+"\$\>")

Any help would be great, thanks

Are you trying to pass in paramters? Or just trying to interpolate the variable name into the string?

The latter is super-simple:
code:
url = 'http://www.somewhere.com/some_other_crap%s' % string_variable
The former is more difficult (though still relatively simple) but doesn't seem like what you want.

quote:

Also i'm having another problem..

I'm trying to generate a xml file.
I can generate an xml file, However the content is hardcoded in the python script.

like so
code:
 #create a <type> element
paragraph2 = xml.createElement("type")
maincard.appendChild(paragraph2)

#Give type text
typeText = xml.createTextNode("Show")
paragraph2.appendChild(typeText)
How should i go about getting the HTML that i scraped using BeauituflSoup from another script and generating an xml file from it?
HTML pretty much is XML (and XHTML absolutely is XML), what do you need to do this for?

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

leinad posted:

code:
for e, k in enumerate(i): 
  val = 1 
  for f, j in enumerate(i): 
    if e != f: 
      val *= (-x[j] * inverse(x[k] - x[j], p)) 
  M += y[k] * val

return M % p 

There's not too much you can do, other than making your variable names more descriptive. :argh:

Hughmoris
Apr 21, 2007
Let's go to the abyss!
I am trying to teach myself python as my first language, using a tutorial I found on their site called "A Byte of Python". I just reached the section on Lists, and I've hit a bit of a speed bump with a bit of example code. The code is for writing a shopping list, and manipulating it.

code:
#!/usr/bin/python
# Filename: using_list.py
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist), 'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
       print item,
Can someone explain what is going on with the for loop, mainly where "item" is coming from? I don't see it defined anywhere in the program.

hey mom its 420
May 12, 2007

The thing with for loops is that you specify which variable you want each element of the list you're iterating over bound too. So you could just as well do
code:
for snoop_dogg_and_dr_dre in shoplist:
    print snoop_dogg_and_dr_dre,
It would work just nicely, only it's not very descriptive.

oRenj9
Aug 3, 2004

Who loves oRenj soda?!?
College Slice

Hughmoris posted:

Can someone explain what is going on with the for loop, mainly where "item" is coming from? I don't see it defined anywhere in the program.
A list is a type of object that is an iterator, meaning it has multiple values that can be accessed in a specific order. The for x in y: block is just a simplified way of writing*:
code:
shoplist = ['apple', 'mango', 'carrot', 'banana']
i = 0
while i < len(shoplist):
  item = shoplist[i]
  print item
  i += 1
This works because you can access an element in a list using shoplist[3].

* Technically, I think Python for blocks create an iterator then apply the value returned by iter.next() to the desired value. Such as:
code:
shoplist = ['apple', 'mango', 'carrot', 'banana']
it = iter(shoplist)
while True:
  try:
    item = it.next()
    print item
  except StopIteration:
    break
Both of these solutions do the exact same thing as your for item in shoplist:, but the for is much cleaner looking and easier to follow.

oRenj9 fucked around with this message at 19:15 on May 9, 2008

Mulloy
Jan 3, 2005

I am your best friend's wife's sword student's current roommate.
I was talking to a friend last night and he suggested I begin learning python. I just wanted to double check that his advice was correct and maybe see if there are any specific things you guys could add.

Basically I'm going to be creating some SQL databases and I'd like to be able to access them from the web. I was originally thinking of using/learning PHP but I was told Python can accomplish the same tasks and in the end I'll be better off for learning Python versus PHP.

I've been going through the basic tutorials this morning, but I figured I'd double check before I invest any significant time into it.

hey mom its 420
May 12, 2007

Yeah, he was on spot. Python has drivers for mostly any kind of SQL database and can interact with them easily. Also Django is a web framework for Python, which makes it really easy to make web sites and web applications that use databases and all the Python knowledge you have is of course of great use with Django.

Python is so widespread and generally useful that you pretty much can't miss with Python for any kind of use, but especially for web and databases.

Also Google's App Engine is Python. It's a hosting environment for web Python program's by Google, also very cool and hip right now.

Mulloy
Jan 3, 2005

I am your best friend's wife's sword student's current roommate.
Well I'm going through this: http://docs.python.org/tut right now, and I'm going to poke around with the stuff in the OP. Anything you can recommend that'd be more specific to the project I described would be awesome, but one step at a time. And yeah, the guy who mentioned python mentioned the google API engine, but they're full at the moment, so I just downloaded the SDK to toy with once I get there.

Thanks!

Edit: Also, retarded question I'm sure, but the tutorial just has me using the command prompt - is there a preferred editor or environment for python for beginners?

Mulloy fucked around with this message at 20:50 on May 9, 2008

No Safe Word
Feb 26, 2005

Mulloy posted:

Well I'm going through this: http://docs.python.org/tut right now, and I'm going to poke around with the stuff in the OP. Anything you can recommend that'd be more specific to the project I described would be awesome, but one step at a time. And yeah, the guy who mentioned python mentioned the google API engine, but they're full at the moment, so I just downloaded the SDK to toy with once I get there.

Thanks!

Edit: Also, retarded question I'm sure, but the tutorial just has me using the command prompt - is there a preferred editor or environment for python for beginners?

IDLE, the bundled editor with the Python distribution isn't bad for beginners, but you should try out all the popular coding editors and pick one :) I won't name my personal preference here for fear of starting up another thread of those, but there are probably some recommendations in the thread.

oRenj9
Aug 3, 2004

Who loves oRenj soda?!?
College Slice

No Safe Word posted:

IDLE, the bundled editor with the Python distribution isn't bad for beginners, but you should try out all the popular coding editors and pick one :) I won't name my personal preference here for fear of starting up another thread of those, but there are probably some recommendations in the thread.

As an addendum; download wxPython and the associated demos. The demo pack comes with PyCrust (The Flakiest Python Shell), which is like the standard shell, but with more features like being able to see the elements inside of objects in real time. Plus wxPython kicks tk in the balls when it comes to features and usability.

Capnbigboobies
Dec 2, 2004
Is there a good mp3 playback module? Pymedia seems to be only for 2.4 and pygame seems to playback choppy in windows vista.

EDIT: Also while I am at it how about midi playback?

I am still learning, but I am jumping head first into python. I have tried to pick up C/C++ in the past and failed. With python I am really catching on to it. I am working on a crappy rpg game and its up to 230 lines of code and growing. Thats a huge program for me.

Capnbigboobies fucked around with this message at 06:08 on May 10, 2008

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.

Capnbigboobies posted:

Is there a good mp3 playback module? Pymedia seems to be only for 2.4 and pygame seems to playback choppy in windows vista.

EDIT: Also while I am at it how about midi playback?

I am still learning, but I am jumping head first into python. I have tried to pick up C/C++ in the past and failed. With python I am really catching on to it. I am working on a crappy rpg game and its up to 230 lines of code and growing. Thats a huge program for me.
Check out this, and maybe the package index too.

It sounds like you looking for playback in games so maybe trying to diagnose/cure pygame's issues would be best. Other then that if you are looking to make a media player you can play around with gstreamer and its amazing python bindings(win32 packages exist). I made a video player in less then 60 lines of code.

tehk fucked around with this message at 06:39 on May 10, 2008

Capnbigboobies
Dec 2, 2004

tehk posted:

Check out this, and maybe the package index too.

It sounds like you looking for playback in games so maybe trying to diagnose/cure pygame's issues would be best. Other then that if you are looking to make a media player you can play around with gstreamer and its amazing python bindings(win32 packages exist). I made a video player in less then 60 lines of code.

I do plan on adding sound to my game at some point, but really its just text and if anything I would want midi music (for old school effect.)

Well my plan is to make a simple player that grabs files from RSS feeds and plays them. The only problem is I have no idea how to process the RSS file to get the links and then download all the links. The gui (wxpython) + figuring out how to play the music sounds like it will be a lot easier.

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.

Capnbigboobies posted:

I do plan on adding sound to my game at some point, but really its just text and if anything I would want midi music (for old school effect.)

Well my plan is to make a simple player that grabs files from RSS feeds and plays them. The only problem is I have no idea how to process the RSS file to get the links and then download all the links. The gui (wxpython) + figuring out how to play the music sounds like it will be a lot easier.

Ah! Something I know alot about! Python FeedParser is amazing and will allow you to do all the fun RSS stuff. To download all the links check out urllib2, you can write something like wget in 5 lines.

edit: I did some rss stuff for AWN
code:
import feedparser

url="http://example.com/rss"

feed = feedparser.parse(url)

# Then you can get a the 'enclosure' tag of each entry like this
for entry in feed.entries:
    print entry['enclosures']

# getting the file takes something like this
import urllib2

def wget(uri, destination):
    remote_file = urllib2.urlopen(uri)
    local_file = open(destination, 'w')
    data = remote_file.read()
    local_file.write(data)
Anyway the official documentation is amazing.

tehk fucked around with this message at 09:50 on May 10, 2008

Capnbigboobies
Dec 2, 2004

tehk posted:

Ah! Something I know alot about! Python FeedParser is amazing and will allow you to do all the fun RSS stuff. To download all the links check out urllib2, you can write something like wget in 5 lines.

edit: I did some rss stuff for AWN
code:
import feedparser

url="http://example.com/rss"

feed = feedparser.parse(url)

# Then you can get a the 'enclosure' tag of each entry like this
for entry in feed.entries:
    print entry['enclosures']

# getting the file takes something like this
import urllib2

def wget(uri, destination):
    remote_file = urllib2.urlopen(uri)
    local_file = open(destination, 'w')
    data = remote_file.read()
    local_file.write(data)
Anyway the official documentation is amazing.

Thanks I was able to get something similar working to download the rss, but it used just urllib and didn't work all that great. Could I perhaps bug you on AIM to bombard you with beginner questions? I would really like to have somebody more experience to yak with.

EDIT: Sweet that sample code you gave me work great at just finding the links!
EDIT2: I noticed for the wget function not to trash mp3 files local_file needs to be
local_file = open(desination, 'wb')

Capnbigboobies fucked around with this message at 10:34 on May 10, 2008

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.

Capnbigboobies posted:

Thanks I was able to get something similar working to download the rss, but it used just urllib and didn't work all that great. Could I perhaps bug you on AIM to bombard you with beginner questions? I would really like to have somebody more experience to yak with.

Yea. The reason 'wb' is needed on your platform is covered here, basically its how windows handles binary files(compared to other platforms python works on).

tehk fucked around with this message at 03:43 on May 15, 2008

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


karuna posted:

Hey, how do you pass a variable within a URL?

I am using urllib2

code:
urllib2.urlopen('http://www.somewhere.com/some_other_crap<$MYVAR&>')
This isn't working for me at all, i have also tried %MYVAR and ("\<\$"+"MYVAR"+"\$\>")

Any help would be great, thanks

Check out the official documentation on urllib and urllib2 (http://docs.python.org/lib/module-urllib2.html) specifically the part about urllib2.urlopen() and urllib.urlencode(). That should answer most of your questions. I've worked with these libraries extensively and have encountered pretty much every conceivable problem that could come up with them.

deedee megadoodoo fucked around with this message at 18:53 on May 10, 2008

leinad
Jan 14, 2003

I'm teaching myself a little bit about wxPython, so I'm implementing the calculator from this tutorial except I'll make it evaluate postfix expressions. Anyway, do I have to create a new event handler function for each number and operator button in order to append the symbol to the end of the text box, or is there a way to do it in a single function? Could I set the id of each number button to its value and get the id in the handler? Then use 11-14 for the operators?

trashmatic
Jan 27, 2006

leinad posted:

Anyway, do I have to create a new event handler function for each number and operator button in order to append the symbol to the end of the text box, or is there a way to do it in a single function? Could I set the id of each number button to its value and get the id in the handler?
I don't know whether you can do that exactly, but using unique event handler functions doesn't need to be a lot of work at all. All you need to do is write a function that takes a symbol and returns an event handler function to put that symbol in the box.

code:
def make_append_fn(symbol):
    def handler(event):
        yourwidget.append(symbol)
    return handler
Then you can just put all your symbols and corresponding button IDs in a dict or a list of tuples or whatever and iterate through, creating and attaching a handler function for each button.

code:
symbol_buttons = [('+', 11), ('7', 13)]
for symbol, button_id in symbol_buttons:
    wx.bindfunctiontowidget(button_id, make_append_fn(symbol))

Hughmoris
Apr 21, 2007
Let's go to the abyss!
As I mentioned above, I am still extremely new to python and writing code in general.

With that said, I've encountered another hiccup. I am working on a project Euler problem where I need to calculate a huge number, then add all the digits in that number. I have succeeded in calculating the number, but I'm a tad unsure how to add up the digits that compose that number.

*disclaimer: I'm a little shaky on my terminology, so forgive me.

I am thinking I should break my huge integer into a list, so that each digit in my huge number takes up an element. I can then do a loop on my list that will give me a summation of every element in the list, which in turn is my final answer.


Is my idea doable, or am I approaching it in the wrong way? If it is possible, how do I turn an integer into a list?

bitprophet
Jul 22, 2004
Taco Defender
code:
[email]jeff@jeff.loca[/email]l:~ $ ipython 

In [1]: sum([int(x) for x in str(1234567890)])
Out[1]: 45
sum() does what you'd think, it sums a list, e.g. sum([1,2,3]) = 6. So that's how you sum up a bunch of numbers.

Strings in Python are actually sequences, meaning they're very list-like and can be iterated over just like a list, with for loops and etc. So str(some_integer) is how you get all the digits of a given integer, as a sequence.

Of course, you then have to call int() on the individual list items to get them back into integers, otherwise it's rather difficult to sum them :) Python will not automagically let you do things like 1 + "1" like PHP might do. This is a good thing! PHP's way of doing things leads to horribly hard to find bugs, and promotes sloppiness.

Finally, you can make a one-line equivalent to a for loop with a list comprehension, namely [expression for item in sequence] where expression is just something that returns a value, item is your loop variable name, and sequence is some sort of sequence - a list, a string, etc, or some expression evaluating to one.

Putting it all together does exactly what you seem to be asking for...hope it makes sense :)

Mashi
Aug 15, 2005

Just wanted you to know your dinner's cold and the children all agree you're a shitheel!
Hm, I read about list comprehensions last night and thought I'd give them a go. What I'm trying to do is create a dictionary from a list, using a comprehension:

code:
[(dict[(x,y)] = data[x][y]) for x in range(0,10) for y in range(0,10)]
However it doesn't seem to want me to perform an assignation.. Is there a (preferably not too hack-ish) way?

edit: I suppose this is better suited to my specific purpose, since I am not fussed about the actual return value of the comprehension:

code:
for x in range(0,10): for y in range(0,10): dict[(x,y)] = data[x][y]

Mashi fucked around with this message at 22:20 on May 14, 2008

hey mom its 420
May 12, 2007

try
code:
dict(((x,y),data[x][y]) for x in range(0,10) for y in range(0,10))
You can pass a generator expression (that's like a list comprehension only in parens but it creates a generator) to the dict function. For instance, dict((x,x*2) for x in range(0,4)) will return {0: 0, 1: 2, 2: 4, 3: 6}. dict([(x,x*2) for x in range(0,4)]) would produce an equivalent result, only it would be less efficient. Also dict([(0,0),(1,2),(2,4),(3,6)]) is equivalent to the previous ones.

Also, it's not cool to use dict as a variable name, since the aforementioned function is named that way.

hey mom its 420 fucked around with this message at 23:08 on May 14, 2008

Mashi
Aug 15, 2005

Just wanted you to know your dinner's cold and the children all agree you're a shitheel!
Yea, I found that out! `dict` object not callable, what!?

And thanks that looks like exactly what I wanted! I'm really liking Python. I think I'm going to have fun creating some disgustingly long one liners before I eventually opt for readability like I did with PHP...

Mashi fucked around with this message at 23:21 on May 14, 2008

hey mom its 420
May 12, 2007

Yeah it's really easy to make really powerful one liners with Python, especially with generator expressions and the itertools module. I admit I submit to the urge a bit too often. But when you're just out to quickly make some code to one-tiem calculate something you need, it's great.
For instance, I had a file that had 1 line for every hour in year 2007 and each line had the level of the tide on the Adriatic sea coast at that hour. It took me just 5 lines to read the file and get a list that has 24 values, each representing the average tide level for the hour over a year.

Mashi
Aug 15, 2005

Just wanted you to know your dinner's cold and the children all agree you're a shitheel!
That's great, your program was wider than it was long.

Scaevolus
Apr 16, 2007

bitprophet posted:

code:
$ ipython 
In [1]: sum([int(x) for x in str(1234567890)])
Out[1]: 45
Bonus touched on this, but whenever possible you should use a generator expression instead of a list comprehension, i.e.:
code:
sum(int(x) for x in str(1234567890))   #do this
sum([int(x) for x in str(1234567890)]) #don't do this
The first makes an iterator that takes a constant amount of space, while the second creates the entire list before passing it to sum().

Many functions actually use iterators, even though they are most commonly called with lists.

Scaevolus fucked around with this message at 00:04 on May 15, 2008

hey mom its 420
May 12, 2007

Yeah it's good practice to maximize generator use and minimize lists. Of course it's cool to use lists for stuff you know will be small, but it doesn't cost you anything to use generators and generator expressions, but you will save on memory space when the data sets get big.

Adbot
ADBOT LOVES YOU

bitprophet
Jul 22, 2004
Taco Defender
I'm quite aware of generator expressions, but I've been doing Python since before they existed, and it's very hard to change that particular habit I guess v:shobon:v You're right that they are generally superior to list comps.

  • Locked thread