Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #10724
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: Please code review. |
| Date | 2011-08-02 14:27 +0200 |
| Organization | None |
| References | <4E37E34B.5080707@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1768.1312288021.1164.python-list@python.org> (permalink) |
Karim wrote:
> I need a generator to create the cellname in a excell (using pyuno)
> document to assign value to the correct cell.
Isn't there a way to use a (row, column) tuple directly? If so I'd prefer
that. Also, there used to be an alternative format to address a spreadsheet
cell with something like "R1C2".
> The following code does this but do you have some
> optimizations
> on it, for instance to get the alphabetic chars instead of hard-coding it.
>
> Cheers
> karim
>
> Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
> [GCC 4.5.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def _xrange_cellnames(rows, cols):
> ... """Internal iterator function to compute excell table
> cellnames."""
> ... cellnames = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
> ... for row in xrange(1, rows+1):
> ... for char in cellnames.replace('', ' ').split()[:cols]:
That is interesting ;) But for maximum clarity use
for char in cellnames[:cols]:
instead.
> ... yield char + str(row)
> ...
> >>> list( _xrange_cellnames(rows=3,cols=4))
> ['A1', 'B1', 'C1', 'D1', 'A2', 'B2', 'C2', 'D2', 'A3', 'B3', 'C3', 'D3']
Here's my (untested) attempt to handle columns beyond "Z":
from itertools import chain, count, imap, islice, product
from string import ascii_uppercase
def columnnames():
alpha = (ascii_uppercase,)
return imap("".join, chain.from_iterable(product(*alpha*i) for i in
count(1)))
def cellnames(columns, rows):
for row in xrange(1, rows+1):
for column in islice(columnnames(), columns):
yield column + str(row)
if __name__ == "__main__":
import sys
print list(cellnames(*map(int, sys.argv[1:])))
I think the subject has come up before; goo^h^h^h the search engine of your
choice is your friend.
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Please code review. Peter Otten <__peter__@web.de> - 2011-08-02 14:27 +0200
csiph-web