473,788 Members | 2,857 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Best way to enumerate something in python

Hi Everyone,

I'm wondering about the best way to enumerate something.

I have a list of columnames for a db and I decided to put them in a giant
tuple list for two reasons:
1) its unchangeable
2) I was hoping that creating an enumeration of those names would be easy

In the os.stat there is aparrently a list of things you can refer to eg:
ST_SIZE, ST_ATIME, etc.

How are these defined? They appear to be related to 0,1,2,3,.... some
sort of enumeration.

I would like to create an enumeration with 'friendly names' that map to the
particular offset in my column name tuple.

Thanks,

David
-------
Cell: http://cellphone.duneram.com/index.html
Cam: http://www.duneram.com/cam/index.html
Tax: http://www.duneram.com/index.html

_______________ _______________ _______________ _______________ _____
FREE pop-up blocking with the new MSN Toolbar – get it now!
http://toolbar.msn.click-url.com/go/...ave/direct/01/
Jul 18 '05 #1
2 1711
David,

You may have to give us more detail about what
you want to do, but here goes:

listofcolumns=( 'field1','field 2','field3')
for column in listofcolumns:
<do something>

Most of the time I find that putting the names
in a dictionary with the column name as key and
offset as the value seems to work better.

dictofcolumns={ 'field1':1, 'field2': 2, 'field3':3}

value_for_field 3=row[dictofcolumns['field3']]

For your second question I think you should
take a look at os.path.getatim e, .gmtime, getsize
they are easier to use.

Larry Bates
Syscon, Inc.
"David Stockwell" <wi*******@hotm ail.com> wrote in message
news:ma******** *************** **************@ python.org...
Hi Everyone,

I'm wondering about the best way to enumerate something.

I have a list of columnames for a db and I decided to put them in a giant
tuple list for two reasons:
1) its unchangeable
2) I was hoping that creating an enumeration of those names would be easy
In the os.stat there is aparrently a list of things you can refer to eg:
ST_SIZE, ST_ATIME, etc.

How are these defined? They appear to be related to 0,1,2,3,.... some
sort of enumeration.

I would like to create an enumeration with 'friendly names' that map to the particular offset in my column name tuple.

Thanks,

David
-------
Cell: http://cellphone.duneram.com/index.html
Cam: http://www.duneram.com/cam/index.html
Tax: http://www.duneram.com/index.html

_______________ _______________ _______________ _______________ _____
FREE pop-up blocking with the new MSN Toolbar – get it now!
http://toolbar.msn.click-url.com/go/...ave/direct/01/

Jul 18 '05 #2
David Stockwell wrote:
I have a list of columnames for a db and I decided to put them in a giant
tuple list for two reasons:
1) its unchangeable
2) I was hoping that creating an enumeration of those names would be easy

(...)

I would like to create an enumeration with 'friendly names' that map to the
particular offset in my column name tuple.


Like this?
class tuple_names(tup le): .... def __init__(self, dummy = None):
.... self.__dict__ = dict(zip(self, range(0, len(self))))
.... x = tuple_names(('a ', 'b', 'c'))
x ('a', 'b', 'c') x.c

2
Another approach to enumeration which I've just been playing with:

import sys

class Named_int(int):
"""Named_int('n ame', value) is an int with str() = repr() = 'name'."""
def __new__(cls, name, val):
self = int.__new__(cls , val)
self.name = name
return self
def __str__(self): return self.name
__repr__ = __str__
__slots__ = 'name'

def Enum_dict(_Enum _dest = None, **src):
if _Enum_dest is None:
_Enum_dest = {}
for name, val in src.items():
_Enum_dest[name] = Named_int(name, val)
return _Enum_dest

def Enum(**mapping) :
"""Enum(var = integer, ...) defines the specified named integer variables.
Each variable is set to a Named_int with name 'var' and value 'integer'.
Enum() only works in class bodies and at file level, not in functions."""

Enum_dict(sys._ getframe(1).f_l ocals, **mapping)

# Test
if __name__ == '__main__':
x = Named_int('y', 3)
print x, str(x), int(x), "(%s = %d)" % (x, x)

Enum(
debug = 0,
info = 1,
warning = 2,
error = 3,
critical = 4
)
print"%s = %d" % (info, info)

class foo: Enum (one = 1, two = 2)
print foo.two

print Enum_dict(three = 3, five = 5)
print Enum_dict({None : ()}, seven = 7)

--
Hallvard
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2549
by: Daniel Pryde | last post by:
Hi everyone. I was wondering if anyone might be able to help me out here. I'm currently looking to find the quickest way to find a best fit match in a large array. My problem is that I have an array of, say, 600*400, which contains a value at each point, and I need to find the value in that array which is closest to the input value. It's basically some euclidean distances that I've calculated, and I need to be able to find the best matches...
2
1094
by: David Stockwell | last post by:
I'm going to try using the range function. as in: ID_COL, ANIMAL_COL, HOUSING_COL = range(3) This appears to assign assign those vars as 'constants' with values of 0,1,2 David Stockwell
5
1676
by: Pekka Niiranen | last post by:
Hi, I have Perl code looping thru lines in the file: line: while (<INFILE>) { ... $_ = do something ... if (/#START/) { # Start inner loop
1
1813
by: smichr | last post by:
I see that there is a thread of a similar topic that was posted recently ( enumerate with a start index ) but thought I would start a new thread since what I am suggesting is a little different. I posted a very similar item to python-dev, but they said to post it here. Tutor also said that if anything is to be considered as PEP worthy, it should be run through here first. So...here goes. Whenever I use enumerate, I am doing so...
8
1530
by: andrewfelch | last post by:
I write a lot of code that looks like this: for myElement, elementIndex in zip( elementList, range(len(elementList))): print "myElement ", myElement, " at index: ",elementIndex My question is, is there a better, cleaner, or easier way to get at the element in a list AND the index of a loop than this?
21
1656
by: John Salerno | last post by:
If I want to make a list of four items, e.g. L = , and then figure out if a certain element precedes another element, what would be the best way to do that? Looking at the built-in list functions, I thought I could do something like: if L.index('A') < L.index('D'): # do some stuff But I didn't know if maybe there was a preferred method for this type of
2
2446
by: eight02645999 | last post by:
hi, i am using python 2.1. Can i use the code below to simulate the enumerate() function in 2.3? If not, how to simulate in 2.1? thanks from __future__ import generators def enumerate(sequence): index = 0 for item in sequence: yield index, item
21
2332
by: James Stroud | last post by:
I think that it would be handy for enumerate to behave as such: def enumerate(itrbl, start=0, step=1): i = start for it in itrbl: yield (i, it) i += step This allows much more flexibility than in the current enumerate, tightens up code in many cases, and seems that it would break no
10
3550
by: Debajit Adhikary | last post by:
I'm writing this little Python program which will pull values from a database and generate some XHTML. I'm generating a <tablewhere I would like the alternate <tr>'s to be <tr class="Even"> and <tr class="Odd"> What is the best way to do this?
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10175
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10112
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5399
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3675
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.