list.__len__() or len(list)
which one is better? and why? __len__() is a built-in function of the list object and is updated along with the list object elements and will be useful incase the list is very huge. len() is an external method again, which may require the processing cycles again. Is it right? -- http://mail.python.org/mailman/listinfo/python-list
Re: list.__len__() or len(list)
Christian Heimes wrote: Ian Kelly schrieb: The purpose of obj.__len__() is to implement len(obj), which simply calls it. So obj.__len__() may be faster, but only marginally. The reason to prefer len(obj) is that if you inadvertently pass an object that does not implement __len__, you get the more appropriate TypeError rather than an AttributeError. len(obj) is faster than obj.__len__() for several types like str. In general len() is as least as fast __len__(). len() also does some extra sanity checks. python2.5 -m timeit "'abc'.__len__()" 100 loops, best of 3: 0.453 usec per loop python2.5 -m timeit "len('abc')" 100 loops, best of 3: 0.292 usec per loop Common code paths are already highly optimized. Don't try to be clever unless you really understand what happens inside the interpreter. The __internal__ methods are called magic methods for a reason. ;) Christian Thanks for the useful insight. Then why to have __len__() internal method at all when the built-in len() is faster? I heard, in Python3, this internal method is being pruned/renamed to something else? Can someone please shed light here? Thanks. Nikhil -- http://mail.python.org/mailman/listinfo/python-list
readlines with line number support?
Hi, I am reading a file with readlines method of the filepointer object returned by the open function. Along with reading the lines, I also need to know which line number of the file is read in the loop everytime. I am sure, the line should have the property/attribute which will say the line number of the file. If there is none, do I have to end up using the counter in the loop? fp = open("file", "r") lineno = 0 for line in fp.readlines(): print "line number: " + lineno + ": " + line.rstrip() lineno = lineno + 1 -- Thanks, Nikhil -- http://mail.python.org/mailman/listinfo/python-list
Re: readlines with line number support?
Arnaud Delobelle wrote: Nikhil <[EMAIL PROTECTED]> writes: Hi, I am reading a file with readlines method of the filepointer object returned by the open function. Along with reading the lines, I also need to know which line number of the file is read in the loop everytime. I am sure, the line should have the property/attribute which will say the line number of the file. If there is none, do I have to end up using the counter in the loop? fp = open("file", "r") lineno = 0 for line in fp.readlines(): print "line number: " + lineno + ": " + line.rstrip() lineno = lineno + 1 The standard Python way is using enumerate() for i, line in enumerate(fp): print "line number: " + lineno + ": " + line.rstrip() Oh I did not know enumerate can be used. Thanks Paul and Arnaud. I will try this. -- http://mail.python.org/mailman/listinfo/python-list
Re: readlines with line number support?
Arnaud Delobelle wrote: Nikhil <[EMAIL PROTECTED]> writes: Hi, I am reading a file with readlines method of the filepointer object returned by the open function. Along with reading the lines, I also need to know which line number of the file is read in the loop everytime. I am sure, the line should have the property/attribute which will say the line number of the file. If there is none, do I have to end up using the counter in the loop? fp = open("file", "r") lineno = 0 for line in fp.readlines(): print "line number: " + lineno + ": " + line.rstrip() lineno = lineno + 1 The standard Python way is using enumerate() for i, line in enumerate(fp): print "line number: " + lineno + ": " + line.rstrip() Oh I did not know enumerate can be used. Thanks Paul and Arnaud. I will try this. -- http://mail.python.org/mailman/listinfo/python-list
Re: readlines with line number support?
Arnaud Delobelle wrote: The standard Python way is using enumerate() for i, line in enumerate(fp): print "line number: " + lineno + ": " + line.rstrip() I guess you meant to say : for lineno, line in enumerate(fp): print "line number: " + lineno + ": " + line.rstrip() Thanks. -- http://mail.python.org/mailman/listinfo/python-list
AttributeError: module object has no attribute
I have recently written a small module. When I import the module, I always get the error only when I do >>> from local.my.module import * -- Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '/xyz/py/file' --- but when I do the below, I do not get any error. -- >> import local.my.module >> -- Any ideas on what could be wrong? Thanks in advance. Nikhil -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError: module object has no attribute
Peter Otten wrote: Nikhil wrote: I have recently written a small module. When I import the module, I always get the error only when I do >>> from local.my.module import * -- Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '/xyz/py/file' --- but when I do the below, I do not get any error. -- >> import local.my.module >> -- Any ideas on what could be wrong? Are you abusing the __all__ attribute? $ cat tmp.py __all__ = ['/xyz/py/file'] $ python -c "from tmp import *" Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '/xyz/py/file' Peter Hi Peter, Yes, I am. Is there any reason not to? basically, since this is implemented in the module, I have to export it since the caller to the function in the module is responsible for ensuring he has enough proper permissions to read the file. Thanks, Nikhil -- http://mail.python.org/mailman/listinfo/python-list
preserve history in the interactive python
Hi, I am using python -i, and I find it hard typing/pasting the commands from the previous interactive shell. Basically, is there anyway that I can preserve the history in the shell? I guess but not sure there should be something like ~/.pyrc for configuring such but can someone please let me know what is the effective environment variable to preserve the history? Thanks, Nikhil -- http://mail.python.org/mailman/listinfo/python-list
Re: preserve history in the interactive python
Nikhil wrote: Hi, I am using python -i, and I find it hard typing/pasting the commands from the previous interactive shell. Basically, is there anyway that I can preserve the history in the shell? I guess but not sure there should be something like ~/.pyrc for configuring such but can someone please let me know what is the effective environment variable to preserve the history? Thanks, Nikhil >>there should be something like ~/.pyrc please read it as something in a file pointed by PYTHONSTARTUP environment variable. I am mostly here interested in saving the python shell's history automatically. Nikhil -- http://mail.python.org/mailman/listinfo/python-list
Re: preserve history in the interactive python
Nikhil wrote: Hi, I am using python -i, and I find it hard typing/pasting the commands from the previous interactive shell. Basically, is there anyway that I can preserve the history in the shell? I guess but not sure there should be something like ~/.pyrc for configuring such but can someone please let me know what is the effective environment variable to preserve the history? Thanks, Nikhil I figured it out. This below thing works fine for me. BTW, I got it from http://docs.python.org/tut/node15.html. A little search would not hurt ;-) $ echo $PYTHONSTARTUP /u/me/.pyrc $ cat .pyrc import sys import atexit import os import readline import rlcompleter myprompt='$ ' myhistoryfile="/u/me/.pyhistory" #set the prompt sys.ps1=myprompt #save the history historyPath = os.path.expanduser(myhistoryfile) def save_history(historyPath=historyPath): import readline readline.write_history_file(historyPath) if os.path.exists(historyPath): readline.read_history_file(historyPath) atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError: module object has no attribute
Marc 'BlackJack' Rintsch wrote: On Tue, 20 May 2008 23:31:15 +0530, Nikhil wrote: Peter Otten wrote: Nikhil wrote: I have recently written a small module. When I import the module, I always get the error only when I do >>> from local.my.module import * -- Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '/xyz/py/file' --- but when I do the below, I do not get any error. -- >> import local.my.module >> -- Any ideas on what could be wrong? Are you abusing the __all__ attribute? $ cat tmp.py __all__ = ['/xyz/py/file'] $ python -c "from tmp import *" Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '/xyz/py/file' Yes, I am. Is there any reason not to? That your module raises the `AttributeError` and is broke is not reason enough!? :-) basically, since this is implemented in the module, I have to export it since the caller to the function in the module is responsible for ensuring he has enough proper permissions to read the file. What do you mean by "implemented in the module"? `__all__` is for names that live in the module's namespace -- '/xyz/py/file' isn't even a legal identifier name in Python! Ciao, Marc 'BlackJack' Rintsch. Okay.. thanks :-) I removed the entry from __all__, and I earlier assumed the module to break, but it did not. Thanks again :-) -- http://mail.python.org/mailman/listinfo/python-list
simple way to touch a file if it does not exist
what are the simple ways? I could think of os.open(), os.exec(touch file) are there any simpler methods? -- http://mail.python.org/mailman/listinfo/python-list
Re: simple way to touch a file if it does not exist
bukzor wrote: On May 21, 5:10 pm, "Giampaolo Rodola'" <[EMAIL PROTECTED]> wrote: On 22 Mag, 01:15, Nikhil <[EMAIL PROTECTED]> wrote: what are the simple ways? I could think of os.open(), os.exec(touch file) are there any simpler methods? Just use os.path.exists to check for file existence and open() as replacement for touch. import os if not os.path.exists('file'): ... open('file', 'w').close() ... --- Giampaolohttp://code.google.com/p/pyftpdlib/ As simple as it gets is a single builtin function call: open("somefile.txt", "a") Leave out the ,"a" if you don't mind blanking a pre-existing file. Thanks :-) That reminds me to check if I could quickly nullify a file if it exists if os.path.exists('file'): open('file', 'w').close() Right? -- http://mail.python.org/mailman/listinfo/python-list
Using MySQLdb to select into the local file
I am using the MySQLdb python module. I have a table named 'testing' with few columns, under the 'test' database, what is hosted on a remote mysql server. I want to run the following query to get a comma-seperated information from the table LOCK TABLES foo READ; SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM 'testing' UNLOCK TABLES; ..the query is running fine, but what I am noticing is /tmp/result.txt is getting created locally on a mysqld running machine but not on the client(python program) using the MySQLdb module. I am wondering if anyone has gone through this before and made some arrangements to iterate over the data but get the /tmp/result.txt generated locally on the client machine? On the local or the server file, from http://dev.mysql.com/doc/refman/5.0/en/select.html --- The SELECT ... INTO OUTFILE statement is intended primarily to let you very quickly dump a table to a text file on the server machine. If you want to create the resulting file on some client host other than the server host, you cannot use SELECT ... INTO OUTFILE. In that case, you should instead use a command such as mysql -e "SELECT ..." > file_name to generate the file on the client host. --- So, what is the equivalent of using '-e' mysql commandline option in the MySQLdb python module? I am sorry if this is supposed to go to only MySQL, but not really sure so copying the relevant assumed. Thanks, Nikhil -- http://mail.python.org/mailman/listinfo/python-list
Re: Using MySQLdb to select into the local file
John Nagle wrote: Nikhil wrote: I am using the MySQLdb python module. I have a table named 'testing' with few columns, under the 'test' database, what is hosted on a remote mysql server. I want to run the following query to get a comma-separated information from the table LOCK TABLES foo READ; SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM 'testing' UNLOCK TABLES; ..the query is running fine, but what I am noticing is /tmp/result.txt is getting created locally on a mysqld running machine but not on the client(python program) using the MySQLdb module. Unfortunately, while there is LOAD DATA LOCAL INFILE, which reads a file on the client, there is no SELECT INTO LOCAL OUTFILE. Actually, you probably want to turn off the FILE privilege for your MySQL. That blocks LOAD DATA INFILE and SELECT INTO OUTFILE, generally considered a good idea because those commands can access arbitrary file names. Also, if you're still using LOCK TABLES and UNLOCK TABLES, read up on InnoDB and transactions. Typically, you do something like this: import MySQLdb import csv def writedb(db, filename) : try : outcsv = csv.writer(filename)# output object for CSV cursor = db.cursor() cursor.execute("SELECT a,b,a+b FROM testing") while True :# do all rows row = cursor.fetchone()# get a tuple for one row if row is None :# if end of rows break# done outcsv.writerow(row)# write row in CSV format db.commit()# release locks except MySQLdb.OperationalError, message: print "Database trouble: ", message # handle any db problems raise# reraise exception hostname="???"# fill in appropriately user="???" password="???" db = MySQLdb.connect(host=hostname, # open database user=username, passwd=password, db=databasename) writedb(db, '/tmp/result.txt')# do it === Note that this is ASCII-oriented; if you Unicode, you need extra params to "connect". Also, the CSV module doesn't do Unicode well as yet. Make sure the "outcsv" object goes out of scope before you try to read the file, so the file gets flushed and closed. John Nagle Thanks John. That was a useful tip. Regards, Nikhil -- http://mail.python.org/mailman/listinfo/python-list
make a string a list
or a string iterable ? How can I do that. I have lots of '\r\n' characters in the string which I think can be easier if it were made into a list and I can easily see if the required value (its a numeral) is present in it or not after some position or after some characters' position. Thanks, Nikhil -- http://mail.python.org/mailman/listinfo/python-list
Unconverted data remains
Hi My Problem I have a list :- L = ['Sunday November 11 2012 9:00pm ', 'Thursday November 15 2012 7:00pm ',\ 'Friday November 16 2012 7:00pm ', 'Monday November 19 2012 7:30pm ', \ 'Friday November 23 2012 7:30pm ', 'Sunday November 25 2012 8:00pm ',\ 'Monday November 262012 7:00pm ', 'Thursday November 29 2012 6:30pm ',\ 'Saturday December 1 20125:30pm ', 'Thursday December 6 2012 9:00pm ',\ 'Sunday December 9 2012 7:00pm ', 'Friday November 9 2012 6:00pm ', \ 'Friday November 9 2012 7:00pm ', 'Friday November 9 2012 7:00pm '] final_event_time = [datetime.strptime(iterable, '%A %B %d %Y %I:%M%p') for iterable in L] and having this error Unconverted data remains . I am trying to convert all these in datetime object. -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
random number
Hi All How can we generate a 6 digit random number from a given number ? eg:- def number_generator(id): random.randint(id,99) When i am using this it is sometimes giving me five digit and sometimes 6 . I want to avoid encryption . Can i have alphanumeric 6 digit random number from this . Thanks in advance -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
Re: random number
Hi I want something to achieve like this :- def random_number(id): # I am passing it from request # do something return random_number Output random_number(5) AXR670 One input that is a number in return you are getting 6 digit alphanumeric string. I tried this s = '%06d' % random.randint(0, 99) it gives : '192862' (a string ) Thanks in advance. On Mon, Mar 26, 2012 at 11:47 AM, Daniel da Silva wrote: > If you want it as an int: > random.randint(10, 99) > > Or as a string: > s = '%06d' % random.randint(0, 99) > > > > On Mon, Mar 26, 2012 at 2:08 AM, Nikhil Verma wrote: > >> Hi All >> >> How can we generate a 6 digit random number from a given number ? >> >> eg:- >> >> def number_generator(id): >> random.randint(id,99) >> >> When i am using this it is sometimes giving me five digit and sometimes 6 >> . I want to avoid encryption . Can i have alphanumeric 6 digit random >> number from this . >> >> Thanks in advance >> >> -- >> Regards >> Nikhil Verma >> +91-958-273-3156 >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
Re: random number
Hi Thanks Michael I want exactly wanted this. Great def random_number(id) ...characters = list(string.ascii_lowercase +string.ascii_uppercase +string.digits) I used this this earlier and tried then by using choice . This is great. On Mon, Mar 26, 2012 at 2:54 PM, Michael Poeltl wrote: > * Nikhil Verma [2012-03-26 08:49]: > > Hi > > > > I want something to achieve like this :- > > > > def random_number(id): # I am passing it from request > > # do something > > return random_number > > > > Output > > > > random_number(5) > > AXR670 > > > > One input that is a number in return you are getting 6 digit alphanumeric > > string. > > > > I tried this > > s = '%06d' % random.randint(0, 99) > > > > it gives : '192862' (a string ) > > > > Thanks in advance. > ah - so I misunderstood - I thought you want a permutation of a given > 6-digit number > > It's still not quite clear to me what role 'id' is playing ... so let's > check this one; > and Steven, who is maybe more experienced than I am will help us ufrther > > >>> import random, string > >>> def random_number(id): > ... characters = list(string.ascii_lowercase + > ... string.ascii_uppercase + > ... string.digits) > ... coll_rand = [] > ... for i in range(6): > ... random.shuffle(characters) > ... coll_rand.append(characters[0]) > ... return ''.join(coll_rand) > ... > >>> id = 5 > >>> print (random_number(id)) > puMHCr > >>> > > regards > Michael > > > > > > On Mon, Mar 26, 2012 at 12:10 PM, Michael Poeltl < > > michael.poe...@univie.ac.at> wrote: > > > > > * Nikhil Verma [2012-03-26 08:09]: > > > > Hi All > > > > > > > > How can we generate a 6 digit random number from a given number ? > > > what about this? > > > > > > >>> given_number=123456 > > > >>> def rand_given_number(x): > > > ... s = list(str(x)) > > > ... random.shuffle(s) > > > ... return int(''.join(s)) > > > ... > > > >>> print (rand_given_number(given_number)) > > > 653421 > > > > > > > > > > > -- > > Regards > > Nikhil Verma > > +91-958-273-3156 > > > -- > Michael Poeltl > Computational Materials Physics voice: +43-1-4277-51409 > Univ. Wien, Sensengasse 8/12 fax: +43-1-4277-9514 (or 9513) > A-1090 Wien, AUSTRIA cmp.mpi.univie.ac.at > > --- > ubuntu-11.10 | vim-7.3 | python-3.2.2 | mutt-1.5.21 | elinks-0.12 > > --- > -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to filter a dictionary ?
Thanks Shashank . It worked. On Tue, Apr 10, 2012 at 11:34 AM, Shashank Singh < shashank.sunny.si...@gmail.com> wrote: > > > On Mon, Apr 9, 2012 at 10:49 PM, Nikhil Verma wrote: > >> >> for_patient_type = {37: u'Test', 79: u'Real', 80: u'Real', 81: u'Real', >> 83: u'Real', 84: u'Real', 91: u'Real', 93: u'Real'} >> >> I want if the values are 'Real' give me the keys that have values 'Real' >> like this. >> >> {79:'Real'} >> {80:'Real'} >> {81:'Real'} >> {83:'Real'} >> {84:'Real'} >> {91:'Real'} >> {93:'Real'} >> > > if you want the dict filtered > > Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) > [GCC 4.2.1 (Apple Inc. build 5646)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> for_patient_type = {37: u'Test', 79: u'Real', 80: u'Real', 81: > u'Real', 83: u'Real', 84: u'Real', 91: u'Real', 93: u'Real'} > >>> dict((k, for_patient_type[k]) for k in for_patient_type if > for_patient_type[k] == 'Real') > {79: u'Real', 80: u'Real', 81: u'Real', 83: u'Real', 84: u'Real', 91: > u'Real', 93: u'Real'} > >>> > > If you just want the keys > > >>> [k for k in for_patient_type if for_patient_type[k] == 'Real'] > [80, 81, 83, 84, 91, 93, 79] > >>> > > >> >> I am trying this but its giving me a generator object. >> >> In [9]: (k for k,v in for_patient_type.iteritems() if v == 'Real') >> > > Iterating over a dict gives you all the keys, not the key value pairs > > > > -- > Regards > Shashank Singh > http://www.flipora.com > http://r <http://www.cse.iitb.ac.in/%7Eshashanksingh> > ationalpie.wordpress.com > > -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to filter a dictionary ?
Thanks Dave and Shashank . I cleared the concept also. I got it guys. In my piece of code where i was doing this In [25]: [k for k,v in for_patient_type.iteritems() if v == "Real"] Out[25]: [80, 81, 83, 84, 91, 93, 79] thats what shashank suggest later. Thanks to you Dave.I cleared my concept which i just forgot. On Tue, Apr 10, 2012 at 12:54 PM, Shashank Singh < shashank.sunny.si...@gmail.com> wrote: > > > On Tue, Apr 10, 2012 at 12:16 AM, Dave Angel wrote: > >> On 04/10/2012 02:04 AM, Shashank Singh wrote: >> > On Mon, Apr 9, 2012 at 10:49 PM, Nikhil Verma > >wrote: >> > >> >> I am trying this but its giving me a generator object. >> >> >> >> In [9]: (k for k,v in for_patient_type.iteritems() if v == 'Real') >> >> >> > Iterating over a dict gives you all the keys, not the key value pairs >> > >> >> But that line does not iterate over the dict, it iterates over an >> iterator consisting of key/value pairs. Note he had a call to >> iteritems(). >> > > Thanks Dave. > My bad. Nikhil, you could get the data that you wanted by your initial > approach. All you needed was to either run through the generator or just > use list comprehension > > >>> g = (k for k,v in for_patient_type.iteritems() if v == 'Real') > >>> for k in g: print k > ... > 80 > 81 > 83 > 84 > 91 > 93 > 79 > >>> > > > >>> [k for k,v in for_patient_type.iteritems() if v == 'Real'] > [80, 81, 83, 84, 91, 93, 79] > > > -- > Regards > Shashank Singh > http://www.flipora.com > http://r <http://www.cse.iitb.ac.in/%7Eshashanksingh> > ationalpie.wordpress.com > > -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
DateTime objectFormatting
Hi I am using a DateTimeField in my class and want to do some tweaking with its object. class ClinicVisitDateSettings(models.Model): name = models.CharField(max_length=80,blank=True,null=True) date_created = models.DateTimeField(blank=True,null=True) def __unicode__(self): return "%s %s" % (self.name, self.date_created.strftime("%A %B %d")) The user fills Gen GI in name and date along with time. What i am able to achieve with this class object to return is :- Gen GI Monday May 7 I want that the this class should return object like this :- Gen GI Monday AM, May 7 Pancreas Tuesday PM, May 8 How can achieve AM and PM also ? with this datetime object Thanks in advance -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
Re: DateTime objectFormatting
Thanks On Wed, May 2, 2012 at 8:27 PM, Chris Rebert wrote: > On Wed, May 2, 2012 at 7:49 AM, Nikhil Verma > wrote: > > > def __unicode__(self): > > return "%s %s" % (self.name, self.date_created.strftime("%A %B > %d")) > > > > > > The user fills Gen GI in name and date along with time. > > > > What i am able to achieve with this class object to return is :- > > > > Gen GI Monday May 7 > > > > I want that the this class should return object like this :- > > > > Gen GI Monday AM, May 7 > > Pancreas Tuesday PM, May 8 > > > > How can achieve AM and PM also ? with this datetime object > > Consult the docs. > http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior: > "%p -- Locale’s equivalent of either AM or PM." > > So, strftime("%A %p, %B %d"). > > Regards, > Chris > -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
return respective values when mutiple keys are passed in dictionary
HI All I was clearing my concepts on dictionary and stuck in this problem. I have a dictionary which i have formed by using zip function on two list so that one list (which i have hardcoded) becomes the keys and the other list becomes its values. Now i want to know how can i get the values of keys at once if i pass the keys in a dictionary. Let say I have a dictionary mydict = {'a':'apple' , 'b':'boy' ,'c' : 'cat', 'd':'duck','e':'egg'} Now if i do :- mydict.get('a') 'apple' What i want is some i pass keys in get and in return i should have all the values of those keys which i pass. ## mydict.get('a','b','c')###demo for what i want 'apple','boy','cat'### Output i want # -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
Re: return respective values when mutiple keys are passed in dictionary
Thanks Arnaud List comprehension method really works nicely.sorry for late reply. On Mon, May 7, 2012 at 7:10 PM, Arnaud Delobelle wrote: > On 7 May 2012 12:31, Nikhil Verma wrote: > > HI All > > > > I was clearing my concepts on dictionary and stuck in this problem. > > I have a dictionary which i have formed by using zip function on two > list so > > that one list (which i have hardcoded) becomes the keys and the other > list > > becomes its values. > > > > Now i want to know how can i get the values of keys at once if i pass the > > keys in a dictionary. > > > > Let say I have a dictionary > > > > mydict = {'a':'apple' , 'b':'boy' ,'c' : 'cat', 'd':'duck','e':'egg'} > > > > Now if i do :- > > > > mydict.get('a') > > 'apple' > > mydict['a'] is the usual way to get the value associated with a key. > The difference is that it will throw an exception if the key doesn't > exist, which is most of the time the sanest thing to do. > > > What i want is some i pass keys in get and in return i should have all > the > > values of those keys which i pass. > > > > ## > > mydict.get('a','b','c')###demo for what i want > > 'apple','boy','cat'### Output i want > > # > > 1. You can use a list comprehension > > >>> [mydict[k] for k in 'a', 'b', 'c'] > ['apple', 'boy', 'cat'] > > 2. You can use map (for python 3.X, you need to wrap this in list(...)) > > >>> map(mydict.__getitem__, ['a', 'b', 'c']) > ['apple', 'boy', 'cat'] > > 3. You can use operator.itemgetter > > >>> from operator import itemgetter > >>> itemgetter('a', 'b', 'c')(mydict) > ('apple', 'boy', 'cat') > > -- > Arnaud > -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
tweaking random number
Hi All I want to generate a random number of 8 digits which involve 3 number and 5 digits. Like this :- def random_number(): # do something random_number() "123abcde" # first 3 numbers and 5 letters after the numbers. I am able to generate the random number 8 digit like this:- def random_number(): characters = list(string.ascii_lowercase + string.ascii_uppercase\ + string.digits) coll_rand = [] for i in range(8): random.shuffle(characters) coll_rand.append(characters[0]) return ''.join(coll_rand) This generates like this "Kkrgt56r" Thanks in advance -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
Re:rndom number tweaks
Hi Chris (That's 3 digits and 5 letters) Pretty easy. Do you want to distinguish between uppercase and lowercase letters? No i really don't care for that. I just want first three should be numbers and rest 5 are characters. "123aAbBc" Can you give examples ? -- Forwarded message -- From: Chris Angelico To: python-list@python.org Cc: Date: Wed, 9 May 2012 17:44:00 +1000 Subject: Re: tweaking random number On Wed, May 9, 2012 at 5:01 PM, Nikhil Verma wrote: > Hi All > > I want to generate a random number of 8 digits which involve 3 number and 5 > digits. (That's 3 digits and 5 letters) Pretty easy. Do you want to distinguish between uppercase and lowercase letters? Your current random_number function (btw, I wouldn't call it "number" as it isn't one) is most of one possible solution. Divide it into two parts, one part that generates the digits and another part that generates the letters. Your 'characters' template would thus be different for the two parts. There are other solutions, which involve the generation of less random numbers, but your way will work. ChrisA -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
increment date present list of tuple by weeks python
Hi All I have a list like this :- [ ('7 May monday AM Neuropancreatic'), ('8 May tuesday PM Cardiovascular')] how can i increment date in the above list for the next months on weekly basis ? [ ('7 May monday AM Neuropancreatic'),('14May monday AM Neuropancreatic')('21 May monday AM Neuropancreatic')('28 May monday AM Neuropancreatic'), ('8 May tuesday PM Cardiovascular'),('15 May monday AM Neuropancreatic'),('22 May monday AM Neuropancreatic'),('29 May monday AM Neuropancreatic')] Thanks -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
How can we covert string into Datetime object
Hi All I was going through this link http://docs.python.org/library/datetime.html#strftime-strptime-behavior. I practised strftime() and strptime() functions. Finally i stuck into a situation where i want to get the datetime object so that i can save it in my db. What i want is :- I have a string let say date_created = '11 May Friday PM ' and i want to convert it into datetime object like this datetime.datetime(2012, 5, 11, 4, 12, 44, 24734) Thanks in advance. Any help will be appreciated -- Regards Nikhil Verma +91-958-273-3156 -- http://mail.python.org/mailman/listinfo/python-list
Merge Two List of Dict
Hey guys What is the most optimal and pythonic solution forthis situation A = [{'person_id': '1', 'adop_count': '2'}, {'person_id': '3', 'adop_count': '4'}] *len(A) might be above 10L* B = [{'person_id': '1', 'village_id': '3'}, {'person_id': '3', 'village_id': '4'}] *len(B) might be above 20L* OutPut List should be C = B = [{'adop_count': '2', 'village_id': '3'}, {'adop_count': '4', 'village_id': '4'}] Thanks in advance -- https://mail.python.org/mailman/listinfo/python-list
Fwd: Merge Two List of Dict
Just editing the count it was from Indian place value notation. -- Forwarded message -- From: Nikhil Verma Date: Thu, Dec 1, 2016 at 12:44 PM Subject: Merge Two List of Dict To: python-list@python.org Hey guys What is the most optimal and pythonic solution forthis situation A = [{'person_id': '1', 'adop_count': '2'}, {'person_id': '3', 'adop_count': '4'}] *len(A) might be above 10* B = [{'person_id': '1', 'village_id': '3'}, {'person_id': '3', 'village_id': '4'}] *len(B) might be above 200* OutPut List should be C = B = [{'adop_count': '2', 'village_id': '3'}, {'adop_count': '4', 'village_id': '4'}] Thanks in advance -- [image: --] Nikhil Verma [image: http://]about.me/nikhil_verma <http://about.me/nikhil_verma?promo=email_sig> -- https://mail.python.org/mailman/listinfo/python-list
How to copy the entire outlook message content in python
Hello All, I'm a beginner trying to achieve the below in my python script: Can anyone help me on this? I'm stuck at step2. 1. Input: A locally saved outlook mail (*.msg) path 2. Go to the path and Copy the entire body of the mail 3. Create a new mail and paste the contents into new mail 4. send it manually # # === Script Start == # import win32com.client as win32 ### Functions def getMailBody(msgFile): start_text = "" end_text = "" with open(msgFile) as f: data=f.read() return data[data.find(start_text):data.find(end_text)+len(end_text)] def releaseMail(body, subject, recipient): outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = recipient mail.Subject = subject mail.HtmlBody = body mail.Display(True) ### Main msgFile = "C:\\RELM\\testMsg.msg" mailTo = "mym...@myserver.com" mailSubject = "Test message" mailBody = getMailBody(msgFile) releaseMail(mailBody, mailSubject, mailRecipient) # # Script End === # Below is the error I'm getting. == File "C:\Python\Python38-32\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 924: character maps to -- https://mail.python.org/mailman/listinfo/python-list
Re: Python for a 10-14 years old?
i think that if she starts out with HTML or something it would be easier. I feel it is easier to learn computers when you are younger cos I am 14 now and i started at 12 and the journey has been quite easy. If she can handle a proper language like python then you might as well go ahead. -- http://mail.python.org/mailman/listinfo/python-list
Network Simulator
Hi...I need help to design a network simulator consisting for 5 routers in python...Any help would be appretiated... Thanks.. -- https://mail.python.org/mailman/listinfo/python-list
Re: *.sdf database access
On Saturday, April 21, 2012 6:55:55 AM UTC-4, Alex Willmer wrote: > On Apr 19, 9:18 pm, Page3D wrote: > > Hi, I am trying to connect and access data in a *.sdf file on Win7 > > system using Python 2.7. I have three questions: > > > > 1. What python module should I use? I have looked at sqlite3 and > > pyodbc. However, I can seem to get the connection to the database file > > setup properly. > > I assume you mean SQL Server Compact by *.sdf. However please note > that there are several several file formats matching SDF > http://en.wikipedia.org/wiki/SDF#Computing and explicit is better than > implicit. > > The sqlite3 module won't help - that's for sqlite files, which an > entirely different file format. Wikpedia says of SQL Server Compact > "An ODBC driver for SQL CE does not exist, and one is not planned > either. Native applications may use SQL CE via OLE DB" > http://en.wikipedia.org/wiki/SQL_Server_Compact. I believe the > adodbapi module, part of PyWin32 > http://sourceforge.net/projects/pywin32/files/ > can connect over OLE DB. > > > 2. How can I determine the appropriate connection string? I have > > opened database file in Visual Studio and can see the tables. I don't > > understand where to find the connection string in Visual Studio. > > These look promising http://www.connectionstrings.com/sql-server-2005-ce > > > 3. Assuming a module from (1) above, does anyone have a code snippet > > for connecting to the database and then accessing a varbinary (image) > > in one of the tables of the databese? > > Pass, I'm afraid > > Regards, Alex Thank you for the pywin32 link, I assume the problem/issue must have been resolved as there were not posts further. I could successfully ping to the database and get the desired results, let me know if anybody still needs the connection code. -- https://mail.python.org/mailman/listinfo/python-list
Re: Want to learn Python
On Thursday, August 15, 2013 7:51:43 PM UTC+5:30, prem kumar wrote: > Hi All, > > > > Presently Iam working with QTP(VBscript)..Now planning to learn PYTHON..Could > you please suggest me like is ti good to learn what is the present condition > for Python in IT Companies.. > > Iam not thinking abt only testing purpose even Iam interested to shift to > development side on python.. > > Also if anyone knows abt good coaching institute for the same in Bangalore > can share with me... > > Eagerly waiting for response from the group.. > > > > Thanks, > > Premkumar This web page has all the information you need to learn python. http://net.tutsplus.com/tutorials/the-best-way-to-learn-python/ -- http://mail.python.org/mailman/listinfo/python-list
iterating over a file with two pointers
hi, I want to iterate over the lines of a file and when i find certain lines, i need another loop starting from the next of that "CERTAIN" line till a few (say 20) lines later. so, basically i need two pointers to lines (one for outer loop(for each line in file)) and one for inner loop. How can i do that in python? please help. I am stuck up on this. -- https://mail.python.org/mailman/listinfo/python-list
Re: iterating over a file with two pointers
On Wednesday, September 18, 2013 4:51:51 PM UTC+5:30, Chris Angelico wrote: > On Wed, Sep 18, 2013 at 9:12 PM, nikhil Pandey > wrote: > > > hi, > > > I want to iterate over the lines of a file and when i find certain lines, i > > need another loop starting from the next of that "CERTAIN" line till a few > > (say 20) lines later. > > > so, basically i need two pointers to lines (one for outer loop(for each > > line in file)) and one for inner loop. How can i do that in python? > > > please help. I am stuck up on this. > > > > After the inner loop finishes, do you want to go back to where the > > outer loop left off, or should the outer loop continue from the point > > where the inner loop stopped? In other words, do you want to locate > > overlapping sections, or not? Both are possible, but the solutions > > will look somewhat different. > > > > ChrisA Hi Chris, After the inner loop finishes, I want to go back to the next line from where the outer loop was left i.e the lines of the inner loop will be traversed again in the outer loop. 1>>I iterate over lines of the file 2>> when i find a match in a certain line, i start another loop till some condition is met in the subsequent lines 3>> then i come back to where i left and repeat 1(ideally i want to delete that line in inner loop where that condition is met, but even if it is not deleted, its OK) -- https://mail.python.org/mailman/listinfo/python-list
Re: iterating over a file with two pointers
On Wednesday, September 18, 2013 5:14:10 PM UTC+5:30, Peter Otten wrote: > nikhil Pandey wrote: > > > > > hi, > > > I want to iterate over the lines of a file and when i find certain lines, > > > i need another loop starting from the next of that "CERTAIN" line till a > > > few (say 20) lines later. so, basically i need two pointers to lines (one > > > for outer loop(for each line in file)) and one for inner loop. How can i > > > do that in python? please help. I am stuck up on this. > > > > Here's an example that prints the three lines following a line containing a > > '*': > > > > Example data: > > > > $ cat tmp.txt > > alpha > > *beta > > *gamma > > delta > > epsilon > > zeta > > *eta > > > > The python script: > > > > $ cat tmp.py > > from itertools import islice, tee > > > > with open("tmp.txt") as f: > > while True: > > for outer in f: > > print outer, > > if "*" in outer: > > f, g = tee(f) > > for inner in islice(g, 3): > > print " ", inner, > > break > > else: > > break > > > > The script's output: > > > > $ python tmp.py > > alpha > > *beta > > *gamma > > delta > > epsilon > > *gamma > > delta > > epsilon > > zeta > > delta > > epsilon > > zeta > > *eta > > $ > > > > As you can see the general logic is relatively complex; it is likely that we > > can come up with a simpler solution if you describe your actual requirement > > in more detail. hi, I want to iterate in the inner loop by reading each line till some condition is met.how can i do that. Thanks for this code. -- https://mail.python.org/mailman/listinfo/python-list
Re: [TYPES] The type/object distinction and possible synthesis of OOP and imperative programming languages
>If you have trouble getting hold of "The Essence of Algol", ... There seems to be a downloadable copy at: www.cs.cmu.edu/~crary/819-f09/Reynolds81.ps It's in PostScript, which is easily convertible to PDF if you wish. Nikhil On Wed, Apr 17, 2013 at 5:30 AM, Uday S Reddy wrote: > [ The Types Forum, http://lists.seas.upenn.edu/mailman/listinfo/types-list] > > Mark Janssen writes: > > > From: en.wikipedia.org: Programming_paradigm: > > > > "A programming paradigm is a fundamental style of computer > > programming. There are four main paradigms: object-oriented, > > imperative, functional and declarative. Their foundations are distinct > > models of computation: Turing machine for object-oriented and > > imperative programming, lambda calculus for functional programming, > > and first order logic for logic programming." > > > > While I understand the interest in purely theoretical models, I wonder > > two things: 1) Are these distinct models of computation valid? And, > > 2) If so, shouldn't a theory of types announce what model of > > computation they are working from? > > These distinctions are not fully valid. > > - Functional programming, logic programming and imperative programming are > three different *computational mechanisms*. > > - Object-orientation and abstract data types are two different ways of > building higher-level *abstractions*. > > The authors of this paragraph did not understand that computational > mechanisms and higher-level abstractions are separate, orthogonal > dimensions > in programming language design. All six combinations, obtained by picking > a > computational mechanism from the first bullet and an abstraction mechanism > from the second bullet, are possible. It is a mistake to put > object-orientation in the first bullet. Their idea of "paradigm" is vague > and ill-defined. > > Cheers, > Uday Reddy > -- http://mail.python.org/mailman/listinfo/python-list