f

#### { '0':'c->c->a' ,'1':'a->b->a' .........}

Hi,

have anybody a hint , how i get a dict from non unique id's and their
different related values.

Chris

###random data #
a=range(10)*3
def seqelem():
i=random.randint(0,2)
elem=['a','b','c'][i]
return elem

s=[seqelem() for t in  range(30)]
print zip(a,s)

## favored result:
{ '0':'c->c->a' ,'1':'a->b->a' .........}


 0
chris
11/7/2010 8:24:20 PM
comp.lang.python 77058 articles. 6 followers.

4 Replies
1270 Views

Similar Articles

[PageSpeed] 49

Hi Chris,

I may have time to look at the rest of your code later.  For now I
just want to comment on one line:

On Nov 7, 12:24=A0pm, chris <oz...@web.de> wrote:

> =A0 =A0 elem=3D['a','b','c'][i]

The string type, just like the list type, is a sequence type. So
strings have all the standard sequence methods.  You could just write:

elem =3D "abc"[i]


 0
John
11/7/2010 8:32:46 PM
chris <ozric@web.de> writes:

> Hi,
>
> have anybody a hint , how i get a dict from non unique id's and their
> different related values.
>
> Chris
>
> ###random data #
> a=range(10)*3
> def seqelem():
>     i=random.randint(0,2)
>     elem=['a','b','c'][i]
>     return elem
>
> s=[seqelem() for t in  range(30)]
> print zip(a,s)
>
> ## favored result:
> { '0':'c->c->a' ,'1':'a->b->a' .........}

Here's one way:

>>> import random
>>>
>>> a=range(10)*3
>>> def seqelem():
....     i=random.randint(0,2)
....     elem=['a','b','c'][i]
....     return elem
....
>>> s=[seqelem() for t in  range(30)]
>>> z = zip(a, s)
>>> print z
[(0, 'b'), (1, 'a'), (2, 'b'), (3, 'a'), (4, 'b'), (5, 'c'), (6, 'b'), (7, 'c'), (8, 'b'), (9, 'b'), (0, 'a'), (1, 'b'), (2, 'b'), (3, 'c'), (4, 'c'), (5, 'b'), (6, 'c'), (7, 'a'), (8, 'a'), (9, 'c'), (0, 'b'), (1, 'c'), (2, 'b'), (3, 'a'), (4, 'c'), (5, 'a'), (6, 'c'), (7, 'b'), (8, 'c'), (9, 'c')]
>>>
>>> from itertools import groupby
>>> from operator import itemgetter
>>>
>>> z.sort(key=itemgetter(0))
>>> print dict((k, '->'.join(map(itemgetter(1), it)))
....            for k, it in groupby(z, itemgetter(0)))
{0: 'b->a->b', 1: 'a->b->c', 2: 'b->b->b', 3: 'a->c->a', 4: 'b->c->c', 5: 'c->b->a', 6: 'b->c->c', 7: 'c->a->b', 8: 'b->a->c', 9: 'b->c->c'}

HTH

--
Arnaud

 0
Arnaud
11/7/2010 8:51:50 PM
chris wrote:
> have anybody a hint , how i get a dict from non unique id's and their
> different related values.
>
> Chris
>
> ###random data #
> a=range(10)*3
> def seqelem():
>     i=random.randint(0,2)
>     elem=['a','b','c'][i]
>     return elem
>
> s=[seqelem() for t in  range(30)]
> print zip(a,s)
>
> ## favored result:
> { '0':'c->c->a' ,'1':'a->b->a' .........}

>>> import random
>>> from collections import defaultdict
>>> a = range(10)*3
>>> s = [random.choice("abc") for _ in a]
>>> d = defaultdict(list)
>>> for k, v in zip(a, s):
....     d[k].append(v)
....
>>> d
defaultdict(<type 'list'>, {0: ['b', 'a', 'a'], 1: ['c', 'a', 'c'], 2: ['c',
'c', 'c'], 3: ['c', 'a', 'a'], 4: ['b', 'c', 'a'], 5: ['b', 'c', 'c'], 6:
['c', 'a', 'b'], 7: ['b', 'b', 'a'], 8: ['a', 'c', 'c'], 9: ['b', 'a',
'b']})
>>> dict((k, "->".join(v)) for k, v in d.iteritems())
{0: 'b->a->a', 1: 'c->a->c', 2: 'c->c->c', 3: 'c->a->a', 4: 'b->c->a', 5:
'b->c->c', 6: 'c->a->b', 7: 'b->b->a', 8: 'a->c->c', 9: 'b->a->b'}

Peter

 0
Peter
11/7/2010 9:00:38 PM
Since your keys are not unique, I would think that you would want a list
of values for the object corresponding to each key.  Something like

Mydict =3D {}

Mydict.setdefault(mykey, []).append(avalue)

-----Original Message-----
Behalf Of Peter Otten
Sent: Sunday, November 07, 2010 4:01 PM
To: python-list@python.org
Subject: Re: { '0':'c->c->a' ,'1':'a->b->a' .........}

chris wrote:
> have anybody a hint , how i get a dict from non unique id's and their
> different related values.
>=20
> Chris
>=20
> ###random data #
> a=3Drange(10)*3
> def seqelem():
>     i=3Drandom.randint(0,2)
>     elem=3D['a','b','c'][i]
>     return elem
>=20
> s=3D[seqelem() for t in  range(30)]
> print zip(a,s)
>=20
> ## favored result:
> { '0':'c->c->a' ,'1':'a->b->a' .........}

>>> import random
>>> from collections import defaultdict
>>> a =3D range(10)*3
>>> s =3D [random.choice("abc") for _ in a]
>>> d =3D defaultdict(list)
>>> for k, v in zip(a, s):
....     d[k].append(v)
....
>>> d
defaultdict(<type 'list'>, {0: ['b', 'a', 'a'], 1: ['c', 'a', 'c'], 2:
['c',=20
'c', 'c'], 3: ['c', 'a', 'a'], 4: ['b', 'c', 'a'], 5: ['b', 'c', 'c'],
6:=20
['c', 'a', 'b'], 7: ['b', 'b', 'a'], 8: ['a', 'c', 'c'], 9: ['b', 'a',=20
'b']})
>>> dict((k, "->".join(v)) for k, v in d.iteritems())
{0: 'b->a->a', 1: 'c->a->c', 2: 'c->c->c', 3: 'c->a->a', 4: 'b->c->a',
5:=20
'b->c->c', 6: 'c->a->b', 7: 'b->b->a', 8: 'a->c->c', 9: 'b->a->b'}

Peter
--=20
http://mail.python.org/mailman/listinfo/python-list


 0
Sells
11/9/2010 12:57:35 PM

Similar Artilces:

converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2
Hello, I'm importing large text files of data using csv. I would like to add some more auto sensing abilities. I'm considing sampling the data file and doing some fuzzy logic scoring on the attributes (colls in a data base/ csv file, eg. height weight income etc.) to determine the most efficient 'type' to convert the attribute coll into for further processing and efficient storage... Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello there' '100,000,000,000'], [next row...] ....] Aside from a missing attribu...

'^=' and '~='?
Hello, What is the difference between '^=' and '~='? Thanks, Duckhye ...

if ('A:B:C' =~ /:(.*?)$/) then why the heck is$1 'B:C' and not just 'C'
To repeat the title, in case it is munged by Google Groups: if ('A:B:C' =~ /:(.*?)$/) then why the heck is$1 'B:C' and not just 'C' I've been developing with perl for years; but even simple things in it still sometimes throw up surprises. The regexp /:(.*?)$/ is anchored on the right by$, then comes a non- greedy match which, AIUI, is the "shortest string it can get away with", preceded by a colon. So I would expect this to pick up just the "C", as it does with /([^:]*)$/. Am I assuming/doing something silly? It is frid... gui/GUIDE 'Tools' -> 'Gui options' -> 'Resize behavior: Proportional' Hi everyone I have a question about the 'Tools' -> 'Gui options' -> 'Resize behavior: Proportional' function of GUIDE. I tried to do the same by adding the following code to the _OpeningFcn of my GUIDE-generated gui: hUnits = findobj('-property', 'units'); set(hUnits, 'units', 'normalized'); set(h.figure1, 'resize', 'on'); set(h.figure1, 'position', [0, 0, .9, .9]); movegui(h.figure1, 'center'); This did not work. What is it, that the 'Resize behavior: Proportional' does a... '''''''''''''The Running Update/Append Queries Using VBA code Ordeal'''''''''''''' Hello fellow programmers, I am trying to run an append/update query from code, a command button on a form initiates the queries. the format i am using is; _____________________________________________________ SELECT "criteria" FROM "criteria" WHERE "criteria" UPDATE/APPEND "field selections" RecordSource "qryExample" = above text strings" _______________________________________________________________________ When i am running a SELECT query in this manner it works fine with no problems, and accepts the values of specified linked for... FoxPro '.' and xHarbour '->' In FoxPro you can use '.' and '->' interchangeably when addressing a field in another work area: replace first with subs.first_name ...and.. replace first with subs->first_name ...are equivalent. I can give xHarbour this feature with.. #translate <a>.<b> => <a>-><b> ...at the top of the .prg before the procedure declaration. Is there any problem with this approach? I am still unable to translate the FoxPro.. eof('work') ...to our.. work->(eof()) I assume it's possible and that I've missed something. -- Joe Wrigh... '''''''''''''The Running Update/Append Queries Using VBA code Ordeal'''''''''''''' #2 Hi, Thanks for ur help there HJ. I know how to do the tasks you specified there. I would like for the update query to use field values from some of the fields on the form (frmInvoices) such as InvoiceNumber, DateFrom, DateTo. My problem is that an append/update query can't find the values in the open Form (frmInvoices) when I specify them as; [Forms]![frmInvoices]![InvoiceNumber] a select query has no problem finding the field values on a form. please help. Aaron Hi Aaron, Could you post the entire code that you are having trouble with? Now it is not possible to see what goes wrong. HJ "Aaron" <aaron@rapid-motion.co.uk> wrote in message news:260d7f40.0408120245.2f3d01f8@posting.google.com... > Hi, > > Thanks for ur help there HJ. > > I know how to do the tasks you specified there. > > I would like for the update query to use field values from some of the > fields on the form (frmInvoices) such as InvoiceNumber, DateFrom, > DateTo. My problem is that an append/update query can't find the > values in the open Form (frmInvoices) when I specify them as; > > [Forms]![frmInvoices]![InvoiceNumber] > > a select query has no problem finding the field values on a form. > > please help. > > Aaron First off, if you are not always using all the parameters specified in your form, then you have to add parameters to your query on the fly. Also, you can't just do something like qdf.SQL = "SE... if str_mo not in ('','.') and str_da not in ('','.') and str_yy not in ('','.') Any shorter ? Hi, there. =20 I'm just curious if it ever dawned on anybody how to abbreviate this line : if str_mo not in ('','.') and str_da not in ('','.') and str_yy not in ('','.')=20 =20 Igor Kurbeko Clinical Programmer Analyst 678 336 4328 ikurbeko@atherogenics.com =20 no brain no pain =20 how about: if not (str_mo in ('','.') or str_da in ('','.') or str_yy in ('','.')) OR if not (missing(str_mo) or missing(str_da) or missing(str_yy)) Eric On 22 Oct 03 21:13:37 GMT, ikurbeko@ATHER... FYI: [a,b].join('') !== '' + a + b; // for some 'a' and 'b' Hi I was expecting [a, b, c].join(''); to be equal to '' + a + b + c; but they are not. I read Flanagan's Rhino book, and it told me that Array.join() returns "The string that results from converting each element of |array| to a string and then concatenating them together, with the |separator| string between the elements." But according to http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf === 15.4.4.5 Array.prototype.join (separator) The elements of the array are converted to strings, and these strings are then concatenated... A function with 'and' , 'not' , 'null' , 'car' and 'cdr' What's this ? (defun enigma (x) (and (not (null x)) (or (null (car x)) (enigma (cdr x))))) "I suppose I should learn Lisp, but it seems so foreign." - Paul Graham, Nov 1983 On Wed, Oct 07 2015, CAI GENGYANG wrote: > What's this ? > > > (defun enigma (x) > (and (not (null x)) > (or (null (car x)) > (enigma (cdr x))))) Bad taste? It returns T if the list X contains nil as an element. It would be clearer to write (some #'null x). Helmut CAI GENGYANG ... Calling 'foo.c' or 'foo2.c' from my 'main_code.c' Hello. I don't know if following is possible. I've got 'main_code.c': ............................ char * another_code; another_code = "foo.c"; ............................ I've got 'foo.c': ............................ #include <stdio.h> int main() { printf ("Hello world from 'foo.c'!\n"); return 0; } ............................ I would like to call 'foo.c' main function from 'main_code.c'. Is this possible? Thank you very much and best regards. Francesco Moi <francescomoi@europe.com> scribbled the ... what's this? '->' All, I know that '->' is used in object oriented PHP, but I saw this in the Moodle code (www.moodle.org)$CFG->dbtype = 'mysql'; // mysql or postgres7 (for now) $CFG->dbhost = 'localhost'; // eg localhost or db.isp.com$CFG->dbname = 'moodle'; // database name, eg moodle $CFG->dbuser = 'root'; // your database username$CFG->dbpass = 'mypassword'; // your database password $CFG->prefix = 'mdl_'; // Prefix to use for all table names You can "echo$CFG->dbtype;"...

Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']?
Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? The range() just can generate the numeric list. On Apr 9, 2007, at 3:29 AM, =E4=BA=BA=E8=A8=80=E8=90=BD=E6=97=A5=E6=98=AF=E5= =A4=A9=E6=B6=AF=EF=BC=8C=E6=9C=9B=E6=9E=81=E5=A4=A9=E6=B6=AF=E4=B8=8D=20 =E8=A7=81=E5=AE=B6 wrote: > Is there a simple function to generate a list like ['a', 'b', 'c', ... > 'z']? The range() just can generate the numeric list. import string list(string.lowercase) 人言落日是天涯，望极天涯不见家 schrieb: > Is there a simple ...

error: expected '=', ',', ';', 'asm' or '__attrib
Hi I'm trying to compile an ADC Driver & come acrosss the following error. I've no experience writing drivers before, and hence have no clue how to fix it. Hope someone out there has encountered the problem & suggesst a fix for the same. The Error is I get is : qadc.c: At top level: qadc.c:97: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'qadc_read' make: *** [qadc.o] Error 1 [root@localhost qadc]# ########################################################################### ADC Driver Code ########################################################################### #define MODULE #define __KERNEL__ #include <linux/config.h> #include <linux/module.h> #include <linux/kernel.h> /* printk */ #include <linux/fs.h> / #include <linux/errno.h> /* error codes */ #include <linux/types.h> /* size_t */ #include <linux/proc_fs.h> /* proc file system */ #include <linux/fcntl.h> #include <asm/system.h> /* cli, flags */ #include <asm/uaccess.h> /* copy from/to user */ /*Registers to get qadc access*/ volatile unsigned short * qadcmcr = (unsigned short *)0x40190000; volatile unsigned short * qacr0 = (unsigned short *)0x4019000a; volatile unsigned short * qacr1 = (unsigned short *)0x4019000c; volatile unsigned short * qacr2 = (unsigned short *)0x4019000e; volatile unsigned short * qasr0 = (unsigned short *)0x40190010; volatile unsigned short * qasr1...

error: expected '=', ',', ';', 'asm' or '__attrib
Hi I'm trying to compile an ADC Driver & come acrosss the following error. I've no experience writing drivers before, and hence have no clue how to fix it. Hope someone out there has encountered the problem & suggesst a fix for the same. The Error is I get is : qadc.c: At top level: qadc.c:97: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'qadc_read' make: *** [qadc.o] Error 1 [root@localhost qadc]# ########################################################################### ADC Driver Code ##...

['a', 'b'][True] results 'b' But how?
Hi, Can any one please tell me how is the following code is working? ['a','b'] is a list of string, and [True] is list of boolean value. How is it making effect....? <code Python24> >>> ['a','b] [True] 'b' >>> ['a','b'] [False] 'a' >>> ['a','b']['some_string' == r'some_string'] 'b' >>> ['a','b']['some_string' == r'somestring'] 'a' <code> Thanks in advance, regards, kath. In this case, [True] and [False...

Override 'and' and 'or'
Is it possible to override 'and' and/or 'or'? I cannot find a special method for it... __and__ and __rand__ and __or__ and __ror__ are for binary manipulation... any proposals? Have marvelous sunday, Marco Dekker <m.aschwanden@gmail.com> wrote: > Is it possible to override 'and' and/or 'or'? I cannot find a special > method for it... __and__ and __rand__ and __or__ and __ror__ are for > binary manipulation... any proposals? If you want to customize the truth value testing you have to implement __nonzero__ " __nonzero__( self) Call...

Re: '^=' and '~='?
Duckhye, According to the doc ( http://xrl.us/befwjx ) they, and one other set of characters, and the mnemonic 'NE' all represent 'NOT EQUAL'. Art ------- On Wed, 11 Feb 2009 16:52:40 -0600, Duck-Hye Yang <dyang@CHAPINHALL.ORG> wrote: >Hello, >What is the difference between '^=' and '~='? > >Thanks, >Duckhye ...

Replacing ',' with '.'
Hello, I have a huge amount of numbers in a .txt file. The numbers are in the form 2,43252e+1. I need to replace the , with . How should I do this? I'd prefer some import method that does this during the import procedure. -Janne Hi, I guess you import the data as text and convert it then to numbers. Try 'strrep' before you convert the text to numbers. Tobias Jake the Snake schrieb: > Hello, > > I have a huge amount of numbers in a .txt file. The numbers are in the form 2,43252e+1. I need to replace the , with . How should I do this? I'd prefer some import method...

Diff between '{..}' and {'..'}
Hi, Could anyone tell me the difference between ......| awk '{.......}' AND ......| awk {'......'} And also when(in what situation) these are used? Thanks in advance, Anil. 2005-01-12, 22:37(-08), Anil: > Hi, > > Could anyone tell me the difference between > > .....| awk '{.......}' > > AND > > .....| awk {'......'} > > > And also when(in what situation) these are used? > Thanks in advance, [...] The second one should never be used. The difference is at the shell level, not at the awk level. '...' are stro...

'[OFF]' as in 'offensive'???
Hi, given that 'off-topicness' is indicated as '[OT]' and taking a look at those postings that started the threads indicated as '[OFF]' (which may both be seen as being somewhat offensive) may lead to the conclusion that '[OFF]' stands for offensiveness. I don't think that this is the intended meaning so what actually *does* '[OFF]' mean? I never came across that abbreviation before (although I have been around on the USENET for quite some time) but maybe it is worth knowing? Josef 'Jupp' Schugt NOTE: mails >100 KiB ...

Meaning of ':' and '{}'
Hi, Please, can anyone tell me what is meaning of predicates ':' and '{}' ? ---------------- yours Advait Advait wrote: > Hi, > Please, can anyone tell me what is meaning of predicates ':' and '{}' > ? It depends on the context. : is used for module qualification of predicates. Like lists:member(X,L) The curly brackets are used in Definite Clauses Grammars: find the section on DCGs in the manual or google for it and you will find out easily. There are uses of {} as a functor in datastructures also. Cheers Bart Demoen Hello everyone,...

replacement for '{' and '}' ?
I am still playing around with what kind of syntax I would like to mark up my documents. Are there equivalent long substitutes for { and } when they are not used to describe arguments to functions? Something like \begin{group} and \end{group}. In other words, if I could force myself to write, say, \begin{group} \it ... \end{group} instead of {\it ... }, then I believe I could identify from the markup context what is an argument that belongs to a just invoked macro and what is text. {Of course, in this context, \textit{...} would be better.} No more ambiguity whether a in \myfunction{a} i...

Does '!=' equivelent to 'is not'
I'm a bit confusing about whether "is not" equivelent to "!=" if a != b: ... if a is not b: ... What's the difference between "is not" and "!=" or they are the same thing? pirata wrote: > I'm a bit confusing about whether "is not" equivelent to "!=" > > if a != b: > ... > > if a is not b: > ... > > > What's the difference between "is not" and "!=" or they are the same thing? No, they are not the same thing. == and != test to see if the *value* of two variables are the same. Like so: >>> a = 'hello world' >>> b = 'hello world' >>> a == b True a and b both have the value of 'hello world', so they are equal is and is not, however, do not test for value equivalence, they test for object identity. In other words, they test to see if the object the two variables reference are the same object in memory, like so: >>> a is b False a and b are assigned to two different objects that happen to have the same value, but nevertheless there are two separate 'hello world' objects in memory, and therefore you cannot say that a *is* b Now look at this: >>> c = d = 'hello world' >>> c == d True >>> c is d True In this case, they are again the same value, but now the is test also shows that they are the same *object* as well, because...

Web resources about - { '0':'c->c->a' ,'1':'a->b->a' .........} - comp.lang.python

Resources last updated: 3/10/2016 7:48:57 PM