Re: List problem

2012-12-03 Thread John Gordon
In <8c0a3ea9-2560-47eb-a9c7-3770e41fe...@googlegroups.com> 
subhabangal...@gmail.com writes:

> Dear Group,

> I have a list of the following pattern,

> [("''", "''"), ('Eastern', 'NNP'), ('Army', 'NNP'), ('Commander', 'NNP'), (=
> 'Lt', 'NNP'), ('Gen', 'NNP'), ('Dalbir', 'NNP'), ('Singh', 'NNP'), ('Suhag'=
> , 'NNP'), ('briefed', 'VBD'), ('the', 'DT'), ('Army', 'NNP'), ('chief', 'NN=
> '), ('on', 'IN'), ('the', 'DT'), ('operational', 'JJ'), ('preparedness', 'N=
> N'), ('and', 'CC'), ('the', 'DT'), ('security', 'NN'), ('scenario', 'NN'), =
> ('in', 'IN'), ('the', 'DT'), ('eastern', 'NN'), ('region', 'NN'), (',', ','=
> ), ("''", "''"), ('defence', 'NN'), ('spokesperson', 'NN'), ('Group', 'NNP'=
> ), ('Capt', 'NNP'), ('T', 'NNP'), ('K', 'NNP'), ('Singha', 'NNP'), ('said',=
>  'VBD'), ('here', 'RB')]

> Now, as we see it has multiple VBD elements.
> I want to recognize,count and index them all.

That depends on exactly what you mean by 'reorganize' and 'index'.  But
here's a start:

items = [("''", "''"), ('Eastern', 'NNP'), ('Army', 'NNP'),
('Commander', 'NNP'), ('Lt', 'NNP'), ('Gen', 'NNP'),
('Dalbir', 'NNP'), ('Singh', 'NNP'), ('Suhag' , 'NNP'),
('briefed', 'VBD'), ('the', 'DT'), ('Army', 'NNP'),
('chief', 'NN'), ('on', 'IN'), ('the', 'DT'),
('operational', 'JJ'), ('preparedness', 'NN'), ('and', 'CC'),
('the', 'DT'), ('security', 'NN'), ('scenario', 'NN'),
('in', 'IN'), ('the', 'DT'), ('eastern', 'NN'), ('region', 'NN'),
(',', ','), ("''", "''"), ('defence', 'NN'),
('spokesperson', 'NN'), ('Group', 'NNP'), ('Capt', 'NNP'),
('T', 'NNP'), ('K', 'NNP'), ('Singha', 'NNP'), ('said', 'VBD'),
('here', 'RB')]

vbds = [item[0] for item in items if item[1] == 'VBD']

print vbds
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List problem

2012-12-03 Thread Neil Cerutti
On 2012-12-02, Thomas Bach  wrote:
> On Sun, Dec 02, 2012 at 04:16:01PM +0100, Lutz Horn wrote:
>> 
>> len([x for x in l if x[1] == 'VBD'])
>> 
>
> Another way is
>
> sum(1 for x in l if x[1] == 'VBD')
>
> which saves the list creation.

To also index them:

vbdix = [i for i, a in emumerate(l) if a[1] == 'VBD']
vbdno = len(indices)

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List problem

2012-12-02 Thread subhabangalore
On Sunday, December 2, 2012 9:29:22 PM UTC+5:30, Thomas Bach wrote:
> On Sun, Dec 02, 2012 at 04:16:01PM +0100, Lutz Horn wrote:
> 
> > 
> 
> > len([x for x in l if x[1] == 'VBD'])
> 
> > 
> 
> 
> 
> Another way is
> 
> 
> 
> sum(1 for x in l if x[1] == 'VBD')
> 
> 
> 
> which saves the list creation.
> 
> 
> 
> Regards,
> 
>   Thomas.

Thanks. After I posted I got a solution as,
[x for x, y in enumerate(chunk_word) if "/VB" in y]
but you are smarter.
Thanks.
Regards,
Subhabrata. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List problem

2012-12-02 Thread Thomas Bach
On Sun, Dec 02, 2012 at 04:16:01PM +0100, Lutz Horn wrote:
> 
> len([x for x in l if x[1] == 'VBD'])
> 

Another way is

sum(1 for x in l if x[1] == 'VBD')

which saves the list creation.

Regards,
Thomas.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List problem

2012-12-02 Thread Lutz Horn
Him

Am 02.12.2012 um 16:03 schrieb subhabangal...@gmail.com:
> I have a list of the following pattern,
> 
> [("''", "''"), ('Eastern', 'NNP'), ('Army', 'NNP'), ('Commander', 'NNP'), 
> ('Lt', 'NNP'), ('Gen', 'NNP'), ('Dalbir', 'NNP'), ('Singh', 'NNP'), ('Suhag', 
> 'NNP'), ('briefed', 'VBD'), ('the', 'DT'), ('Army', 'NNP'), ('chief', 'NN'), 
> ('on', 'IN'), ('the', 'DT'), ('operational', 'JJ'), ('preparedness', 'NN'), 
> ('and', 'CC'), ('the', 'DT'), ('security', 'NN'), ('scenario', 'NN'), ('in', 
> 'IN'), ('the', 'DT'), ('eastern', 'NN'), ('region', 'NN'), (',', ','), ("''", 
> "''"), ('defence', 'NN'), ('spokesperson', 'NN'), ('Group', 'NNP'), ('Capt', 
> 'NNP'), ('T', 'NNP'), ('K', 'NNP'), ('Singha', 'NNP'), ('said', 'VBD'), 
> ('here', 'RB')]
> 
> Now, as we see it has multiple VBD elements.
> I want to recognize,count and index them all.

len([x for x in l if x[1] == 'VBD'])

Lutz

-- 
This email is signed with a CAcert certificate. https://www.cacert.org/
Please do not send me Microsoft Office/Apple iWork documents.
Send OpenDocument instead! http://fsf.org/campaigns/opendocument/
https://duckduckgo.com/ | http://donttrack.us/ | http://dontbubble.us/



smime.p7s
Description: S/MIME cryptographic signature
-- 
http://mail.python.org/mailman/listinfo/python-list


List problem

2012-12-02 Thread subhabangalore
Dear Group,

I have a list of the following pattern,

[("''", "''"), ('Eastern', 'NNP'), ('Army', 'NNP'), ('Commander', 'NNP'), 
('Lt', 'NNP'), ('Gen', 'NNP'), ('Dalbir', 'NNP'), ('Singh', 'NNP'), ('Suhag', 
'NNP'), ('briefed', 'VBD'), ('the', 'DT'), ('Army', 'NNP'), ('chief', 'NN'), 
('on', 'IN'), ('the', 'DT'), ('operational', 'JJ'), ('preparedness', 'NN'), 
('and', 'CC'), ('the', 'DT'), ('security', 'NN'), ('scenario', 'NN'), ('in', 
'IN'), ('the', 'DT'), ('eastern', 'NN'), ('region', 'NN'), (',', ','), ("''", 
"''"), ('defence', 'NN'), ('spokesperson', 'NN'), ('Group', 'NNP'), ('Capt', 
'NNP'), ('T', 'NNP'), ('K', 'NNP'), ('Singha', 'NNP'), ('said', 'VBD'), 
('here', 'RB')]

Now, as we see it has multiple VBD elements.
I want to recognize,count and index them all.

If any one can kindly suggest.

Regards,
Subhabrata


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Problem

2012-09-23 Thread Chris Angelico
On Mon, Sep 24, 2012 at 10:56 AM, Littlefield, Tyler
 wrote:
> I've not been following this thread fully, but why not just use x=list(y) to
> copy the list?
> The issue is that when you assign i=[1,2,3] and then j = i, j is just a
> reference to i, which is why you change either and the other changes.

The problem is with lists as elements of that list, so the key is deepcopy.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Problem

2012-09-23 Thread Littlefield, Tyler

On 9/23/2012 3:44 PM, jimbo1qaz wrote:

On Sunday, September 23, 2012 2:31:48 PM UTC-7, jimbo1qaz wrote:

I have a nested list. Whenever I make a copy of the list, changes in one affect 
the other, even when I use list(orig) or even copy the sublists one by one. I 
have to manually copy each cell over for it to work.

Link to broken code: http://jimbopy.pastebay.net/1090401

No, actually that's the OK code. http://jimbopy.pastebay.net/1090494 is the 
broken one.


I've not been following this thread fully, but why not just use 
x=list(y) to copy the list?
The issue is that when you assign i=[1,2,3] and then j = i, j is just a 
reference to i, which is why you change either and the other changes.


--
Take care,
Ty
http://tds-solutions.net
The aspen project: a barebones light-weight mud engine:
http://code.google.com/p/aspenmud
He that will not reason is a bigot; he that cannot reason is a fool; he that 
dares not reason is a slave.

--
http://mail.python.org/mailman/listinfo/python-list


Re: List Problem

2012-09-23 Thread jimbo1qaz
On Sunday, September 23, 2012 2:31:48 PM UTC-7, jimbo1qaz wrote:
> I have a nested list. Whenever I make a copy of the list, changes in one 
> affect the other, even when I use list(orig) or even copy the sublists one by 
> one. I have to manually copy each cell over for it to work.
> 
> Link to broken code: http://jimbopy.pastebay.net/1090401

OK, deepcopy fixed it!
And I fixed the catch indexerror thing too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Problem

2012-09-23 Thread Steven D'Aprano
On Sun, 23 Sep 2012 14:31:48 -0700, jimbo1qaz wrote:

> I have a nested list. Whenever I make a copy of the list, changes in one
> affect the other, 

Then you aren't making a copy.

py> first_list = [1, 2, 3]
py> second_list = first_list  # THIS IS NOT A COPY
py> second_list.append()
py> print first_list
[1, 2, 3, ]


> even when I use list(orig) 

Nonsense. Either you are confused, or there is something you aren't 
telling us. Calling list *does* make a copy:

py> first_list = [1, 2, 3]
py> second_list = list(first_list)
py> second_list.append()
py> print first_list
[1, 2, 3]

What aren't you telling us? My guess is that there are TWO lists 
involved, and you're only copying ONE:


py> a = [1, 2, 3]
py> a.append(["ham", "spam", "cheese"])
py> print a
[1, 2, 3, ['ham', 'spam', 'cheese']]
py> b = list(a)  # make a copy of a, but not the contents of a
py> b.append(99)  # change b
py> b[-1].append("tomato")
py> print a
[1, 2, 3, ['ham', 'spam', 'cheese', 'tomato']]

Notice that b is a copy of a: changing b does not change a. But the 
embedded list within a is *not* copied, so whether you append to that 
list via a or b is irrelevant, both see the same change because there is 
only one inner list in two places.

It might be more obvious if you give the shared sublist a name:

c = ['ham', 'spam', 'tomato']
a = [1, 2, 3, c]
b = [1, 2, 3, c]  # a copy of a, but not a copy of c

Now it should be obvious that any changes to c will show up in both a and 
b, regardless of how you change it. All three of these will have the 
exact same effect:

a[-1].append('eggs')
b[-1].append('eggs')
c.append('eggs')


The way to copy lists, and all their sublists, and their sublists, and so 
on all the way down, is with the copy module:

import copy
b = copy.deepcopy(a)

but if you are doing this a lot, (1) your code will be slow, and (2) you 
can probably redesign your code to avoid so many copies.

By the way, instead of dumping lots of irrelevant code on us, please take 
the time to narrow your problem down to the smallest possible piece of 
code. We're volunteers here, and you are not paying us to wade through 
your code trying to determine where your problem lies. That is up to you: 
you narrow down to the actual problem, then ask for help.

Please read http://sscce.org/ for more details of how, and why, you 
should do this.


Thank you.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Problem

2012-09-23 Thread Dave Angel
On 09/23/2012 05:44 PM, jimbo1qaz wrote:
> On Sunday, September 23, 2012 2:31:48 PM UTC-7, jimbo1qaz wrote:
>> I have a nested list. Whenever I make a copy of the list, changes in one 
>> affect the other, even when I use list(orig) or even copy the sublists one 
>> by one. I have to manually copy each cell over for it to work.
>>
>> Link to broken code: http://jimbopy.pastebay.net/1090401
> No, actually that's the OK code. http://jimbopy.pastebay.net/1090494 is the 
> broken one.

I also would prefer an inline posting of the code, but if it's too big
to post here, it's probably too big for me to debug here.

The usual reason for such a symptom is a nested list, where you have
multiple references to the same inner list inside the outer.  When you
change one of those, you change all of them.

alist = [1, 2, 3]
blist = [alist, alist, alist]   #  or blist = alist * 3
print blist
alist.append(49)
print blist

davea@think:~/temppython$ python jimbo.py
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3, 49], [1, 2, 3, 49], [1, 2, 3, 49]]

Solution to this is to make sure that only copies of alist get into
blist.  One way is

blist = [alist[:], alist[:], alist[:]]

More generally, you can get into this type of trouble whenever you have
non-immutable objects inside the list.

Understand, this is NOT a flaw in the language.  It's perfectly
reasonable to be able to do so, in fact essential in many cases, when
you want it to be the SAME item.


-- 

DaveA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Problem

2012-09-23 Thread Chris Angelico
On Mon, Sep 24, 2012 at 7:44 AM, jimbo1qaz  wrote:
> On Sunday, September 23, 2012 2:31:48 PM UTC-7, jimbo1qaz wrote:
>> I have a nested list. Whenever I make a copy of the list, changes in one 
>> affect the other, even when I use list(orig) or even copy the sublists one 
>> by one. I have to manually copy each cell over for it to work.
>>
>> Link to broken code: http://jimbopy.pastebay.net/1090401
>
> No, actually that's the OK code. http://jimbopy.pastebay.net/1090494 is the 
> broken one.

The first thing I'd change about that code is the whole thing of using
try/exec/except to suppress IndexError. Definitely not good code. I'm
not wholly certain, but I think you might run into weird issues with
negative OOBounds indices (since Python treats a negative list index
as counting from the far end).

This is nothing to do with your originally requested issue, which I
can't see the cause of in your script there. But when you assign a
list, you just get another reference to the same list.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Problem

2012-09-23 Thread Oscar Benjamin
On 23 September 2012 22:31, jimbo1qaz  wrote:

> I have a nested list. Whenever I make a copy of the list, changes in one
> affect the other, even when I use list(orig) or even copy the sublists one
> by one. I have to manually copy each cell over for it to work.
> Link to broken code: http://jimbopy.pastebay.net/1090401


There are many things wrong with that code but I can't tell what you're
referring to. Can you paste the code into your post (rather than just a
link to it)? Can you also explain what you want it to do and at what point
it does the wrong thing?

Oscar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Problem

2012-09-23 Thread jimbo1qaz
On Sunday, September 23, 2012 2:31:48 PM UTC-7, jimbo1qaz wrote:
> I have a nested list. Whenever I make a copy of the list, changes in one 
> affect the other, even when I use list(orig) or even copy the sublists one by 
> one. I have to manually copy each cell over for it to work.
> 
> Link to broken code: http://jimbopy.pastebay.net/1090401

No, actually that's the OK code. http://jimbopy.pastebay.net/1090494 is the 
broken one.
-- 
http://mail.python.org/mailman/listinfo/python-list


List Problem

2012-09-23 Thread jimbo1qaz
I have a nested list. Whenever I make a copy of the list, changes in one affect 
the other, even when I use list(orig) or even copy the sublists one by one. I 
have to manually copy each cell over for it to work.
Link to broken code: http://jimbopy.pastebay.net/1090401
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem...

2010-09-29 Thread Shashwat Anand
On Thu, Sep 30, 2010 at 3:20 AM, Rog  wrote:

> On Wed, 29 Sep 2010 05:52:32 -0700, bruno.desthuilli...@gmail.com wrote:
>
> > On 29 sep, 14:17, Steven D'Aprano  >
> > wrote:
> >> On Tue, 28 Sep 2010 20:11:51 +0100, Rog wrote:
> >> > On Tue, 28 Sep 2010 11:59:08 -0700, geremy condra wrote:
> >>
> >> >> On Tue, Sep 28, 2010 at 11:44 AM, Rog  wrote:
> >> >>> Hi all,
> >> >>> Have been grappling with a list problem for hours... a = [2, 3, 4,
> >> >>> 5,.]
> >> >>> b = [4, 8, 2, 6,.]
> >> >>> Basicly I am trying to place a[0], b[0] in a seperate list IF a[2]
> >> >>> and b[2] is present.
> >> >>> I have tried sets, zip etc with no success. I am tackling Euler
> >> >>> projects with Python 3.1, with minimal knowledge, and having to
> >> >>> tackle the language as I progress. Enjoyable frustration  :)
> >>
> >> >> I'm not clear on what your actual problem is, could you restate it?
> >>
> >> >> It sounds like you want to copy the ith element out of a and b into
> >> >> some other list- call it c- when the (i+2)th element meets some
> >> >> condition. What's the condition?
> >>
> >> >> Geremy Condra
> >>
> >> > The condition is that the i-th element is inverted, but not equal. eg
> >> > 4,2 - 2,4 , 34,5 - 5,34 etc.
> >> > Hope that is clearer.
> >>
> >> Clear as mud.
> >>
> >> Perhaps you should given an example. Given input
> >>
> >> a = [2, 3, 4, 5, 6, 7]
> >> b = [4, 8, 2, 6, 10, 42]
> >>
> >> what output are you expecting,
> >
> > AFAICT, the OP expects [2, 4] in this case, but it's not clear what he'd
> > expect for let's say:
> >
> > a = [2, 3, 21, 4, 5, 6, 7]
> > b = [4, 8, 22, 2, 6, 10, 42]
> >
> > (the 'reversed' pair is at i+3, not i+2)
> >
> > or
> >
> > a = [0, 2, 3, 4, 5, 6, 7]
> > b = [3, 4, 8, 2, 6, 10, 42]
> >
> > (the first pair is at pos 1, not 0)
> >
> > or
> >
> > a = [2, 3, 4, 8, 6, 7]
> > b = [4, 8, 2, 3, 10, 42]
> >
> > (there's a second 'non-reversed/reversed' match at positions resp. 1 & 3)
>
>
> It is true that I would have needed any 'non-reversed/reversed' pairs,
> these would have been the amicable pairs I was looking for.
> The method to recognise them eluded me. Eyes are not good enough  :)
> I have now joined Python-List and will follow the correct route.
> I have used a method suggested that has made the problem redundant,
> though it will bug me from now on.
>
> g = []
>
> def divsum(n):
>return sum(i for i in range(1, n) if not n % i)
>

You can optimize divsum. Remember that factors exist in pairs except when
numbers are squares.
Like say 12 have factors = 1, 12, 2, 6, 3, 4
so you can run the loop till sqrt(n) for n since floor(sqrt(n)) = 3 where n
= 12
now factors are , (1, n/1), (2, n/2), (3, n/2).
for a square number say n = 9, the factors are (1, 3, 12)
If you run the loop till sqrt(n) for n since floor(sqrt(n)) = 3 where n = 9
we get the factors as (1, 9), (3, 3)
One of the factor will be redundant, so you need to take care of that.


>
> for x in range(1, 2, -1):
>c = divsum(x)
>v = divsum(c)
>

Can be done as,
c, v = divsum(x), divsum(divsum(x))


>if v == x and v != c:
>g.append(divsum(x))
>

No need for else part, what is the use ?


>else:
>continue
>
> print(sum(g))
>

You could pack this up as,

>>> sum(i for i in range(1, 0, -2) if divsum(divsum(i)) == i and
divsum(i) != i)
31626


> --
> Rog
> http://www.rog.pynguins.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
~l0nwlf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem...

2010-09-29 Thread Rog
On Wed, 29 Sep 2010 05:52:32 -0700, bruno.desthuilli...@gmail.com wrote:

> On 29 sep, 14:17, Steven D'Aprano 
> wrote:
>> On Tue, 28 Sep 2010 20:11:51 +0100, Rog wrote:
>> > On Tue, 28 Sep 2010 11:59:08 -0700, geremy condra wrote:
>>
>> >> On Tue, Sep 28, 2010 at 11:44 AM, Rog  wrote:
>> >>> Hi all,
>> >>> Have been grappling with a list problem for hours... a = [2, 3, 4,
>> >>> 5,.]
>> >>> b = [4, 8, 2, 6,.]
>> >>> Basicly I am trying to place a[0], b[0] in a seperate list IF a[2]
>> >>> and b[2] is present.
>> >>> I have tried sets, zip etc with no success. I am tackling Euler
>> >>> projects with Python 3.1, with minimal knowledge, and having to
>> >>> tackle the language as I progress. Enjoyable frustration  :)
>>
>> >> I'm not clear on what your actual problem is, could you restate it?
>>
>> >> It sounds like you want to copy the ith element out of a and b into
>> >> some other list- call it c- when the (i+2)th element meets some
>> >> condition. What's the condition?
>>
>> >> Geremy Condra
>>
>> > The condition is that the i-th element is inverted, but not equal. eg
>> > 4,2 - 2,4 , 34,5 - 5,34 etc.
>> > Hope that is clearer.
>>
>> Clear as mud.
>>
>> Perhaps you should given an example. Given input
>>
>> a = [2, 3, 4, 5, 6, 7]
>> b = [4, 8, 2, 6, 10, 42]
>>
>> what output are you expecting,
> 
> AFAICT, the OP expects [2, 4] in this case, but it's not clear what he'd
> expect for let's say:
> 
> a = [2, 3, 21, 4, 5, 6, 7]
> b = [4, 8, 22, 2, 6, 10, 42]
> 
> (the 'reversed' pair is at i+3, not i+2)
> 
> or
> 
> a = [0, 2, 3, 4, 5, 6, 7]
> b = [3, 4, 8, 2, 6, 10, 42]
> 
> (the first pair is at pos 1, not 0)
> 
> or
> 
> a = [2, 3, 4, 8, 6, 7]
> b = [4, 8, 2, 3, 10, 42]
> 
> (there's a second 'non-reversed/reversed' match at positions resp. 1 & 3)


It is true that I would have needed any 'non-reversed/reversed' pairs,
these would have been the amicable pairs I was looking for.
The method to recognise them eluded me. Eyes are not good enough  :)
I have now joined Python-List and will follow the correct route.
I have used a method suggested that has made the problem redundant,
though it will bug me from now on.

g = []

def divsum(n):
return sum(i for i in range(1, n) if not n % i)

for x in range(1, 2, -1):
c = divsum(x)
v = divsum(c)
if v == x and v != c:
g.append(divsum(x))
else:
continue

print(sum(g)) 

-- 
Rog
http://www.rog.pynguins.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem...

2010-09-29 Thread bruno.desthuilli...@gmail.com
On 29 sep, 14:17, Steven D'Aprano  wrote:
> On Tue, 28 Sep 2010 20:11:51 +0100, Rog wrote:
> > On Tue, 28 Sep 2010 11:59:08 -0700, geremy condra wrote:
>
> >> On Tue, Sep 28, 2010 at 11:44 AM, Rog  wrote:
> >>> Hi all,
> >>> Have been grappling with a list problem for hours... a = [2, 3, 4,
> >>> 5,.]
> >>> b = [4, 8, 2, 6,.]
> >>> Basicly I am trying to place a[0], b[0] in a seperate list IF a[2] and
> >>> b[2] is present.
> >>> I have tried sets, zip etc with no success. I am tackling Euler
> >>> projects with Python 3.1, with minimal knowledge, and having to tackle
> >>> the language as I progress. Enjoyable frustration  :)
>
> >> I'm not clear on what your actual problem is, could you restate it?
>
> >> It sounds like you want to copy the ith element out of a and b into
> >> some other list- call it c- when the (i+2)th element meets some
> >> condition. What's the condition?
>
> >> Geremy Condra
>
> > The condition is that the i-th element is inverted, but not equal. eg
> > 4,2 - 2,4 , 34,5 - 5,34 etc.
> > Hope that is clearer.
>
> Clear as mud.
>
> Perhaps you should given an example. Given input
>
> a = [2, 3, 4, 5, 6, 7]
> b = [4, 8, 2, 6, 10, 42]
>
> what output are you expecting,

AFAICT, the OP expects [2, 4] in this case, but it's not clear what
he'd expect for let's say:

a = [2, 3, 21, 4, 5, 6, 7]
b = [4, 8, 22, 2, 6, 10, 42]

(the 'reversed' pair is at i+3, not i+2)

or

a = [0, 2, 3, 4, 5, 6, 7]
b = [3, 4, 8, 2, 6, 10, 42]

(the first pair is at pos 1, not 0)

or

a = [2, 3, 4, 8, 6, 7]
b = [4, 8, 2, 3, 10, 42]

(there's a second 'non-reversed/reversed' match at positions resp. 1 &
3)


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem...

2010-09-29 Thread Steven D'Aprano
On Tue, 28 Sep 2010 20:11:51 +0100, Rog wrote:

> On Tue, 28 Sep 2010 11:59:08 -0700, geremy condra wrote:
> 
>> On Tue, Sep 28, 2010 at 11:44 AM, Rog  wrote:
>>> Hi all,
>>> Have been grappling with a list problem for hours... a = [2, 3, 4,
>>> 5,.]
>>> b = [4, 8, 2, 6,.]
>>> Basicly I am trying to place a[0], b[0] in a seperate list IF a[2] and
>>> b[2] is present.
>>> I have tried sets, zip etc with no success. I am tackling Euler
>>> projects with Python 3.1, with minimal knowledge, and having to tackle
>>> the language as I progress. Enjoyable frustration  :)
>> 
>> I'm not clear on what your actual problem is, could you restate it?
>> 
>> It sounds like you want to copy the ith element out of a and b into
>> some other list- call it c- when the (i+2)th element meets some
>> condition. What's the condition?
>> 
>> Geremy Condra
> 
> The condition is that the i-th element is inverted, but not equal. eg
> 4,2 - 2,4 , 34,5 - 5,34 etc.
> Hope that is clearer.

Clear as mud.

Perhaps you should given an example. Given input 

a = [2, 3, 4, 5, 6, 7]
b = [4, 8, 2, 6, 10, 42]

what output are you expecting, and how would you work it out by hand?





-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem...

2010-09-28 Thread Shashwat Anand
On Wed, Sep 29, 2010 at 1:15 AM, rog  wrote:

> Shashwat Anand wrote:
>
>
>>
>> On Wed, Sep 29, 2010 at 12:14 AM, Rog > r...@pynguins.com>> wrote:
>>
>>    Hi all,
>>Have been grappling with a list problem for hours...
>>a = [2, 3, 4, 5,.]
>>b = [4, 8, 2, 6,.]
>>Basicly I am trying to place a[0], b[0] in a seperate list
>>IF a[2] and b[2] is present.
>>
>>
>> You are not exactly clear with your problem statement.
>> Care to elaborate it more.
>>
>>I have tried sets, zip etc with no success.
>>I am tackling Euler projects with Python 3.1, with minimal
>>knowledge, and having to tackle the language as I progress.
>>Enjoyable frustration :)
>>
>>--
>>Rog
>>http://www.rog.pynguins.com
>>--
>>http://mail.python.org/mailman/listinfo/python-list
>>
>>
>>
>>
>> --
>> ~l0nwlf
>>
>
> "Let d(/n/) be defined as the sum of proper divisors of /n/ (numbers less
> than /n/ which divide evenly into /n/).
> If d(/a/) = /b/ and d(/b/) = /a/, where /a/ ≠ /b/, then /a/ and /b/ are an
> amicable pair and each of /a/ and /b/ are called amicable numbers.
>
> For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44,
> 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4,
> 71 and 142; so d(284) = 220.
>
> Evaluate the sum of all the amicable numbers under 1."
>
> from Project Euler.
> I have all answers contained in two lists but need to extract the amicable
> pairs.
> eg
> a = [200, 4, 284,.]
> b = [284, 9, 200, ..]
> Hope that helps.
> Thanks for the link.
>

I am not sure how and what you managed, but what I understand you need to
calculate sum of divisors.
A quick unoptimized solution can be,

>>> def divsum(n):return sum(i for i in range(1, n) if not n % i)... >>> 
>>> divsum(220)284>>> divsum(284)220


Now all is left is looping and little maths, since upper bound is not
high, brute force is Ok.

 http://codepad.org/g6PRyoiV   # For reference

Also I guess you missed 'Reply All', please take care of it next time.


> Rog
>
>


-- 
~l0nwlf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem...

2010-09-28 Thread Rog
On Tue, 28 Sep 2010 11:59:08 -0700, geremy condra wrote:

> On Tue, Sep 28, 2010 at 11:44 AM, Rog  wrote:
>> Hi all,
>> Have been grappling with a list problem for hours... a = [2, 3, 4,
>> 5,.]
>> b = [4, 8, 2, 6,.]
>> Basicly I am trying to place a[0], b[0] in a seperate list IF a[2] and
>> b[2] is present.
>> I have tried sets, zip etc with no success. I am tackling Euler projects
>> with Python 3.1, with minimal knowledge, and having to tackle the
>> language as I progress. Enjoyable frustration  :)
> 
> I'm not clear on what your actual problem is, could you restate it?
> 
> It sounds like you want to copy the ith element out of a and b into some
> other list- call it c- when the (i+2)th element meets some condition.
> What's the condition?
> 
> Geremy Condra

The condition is that the i-th element is inverted, but not equal.
eg 4,2 - 2,4 , 34,5 - 5,34 etc.
Hope that is clearer.
Thanks for the response.
-- 
Rog
http://www.rog.pynguins.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem...

2010-09-28 Thread geremy condra
On Tue, Sep 28, 2010 at 11:44 AM, Rog  wrote:
> Hi all,
> Have been grappling with a list problem for hours...
> a = [2, 3, 4, 5,.]
> b = [4, 8, 2, 6,.]
> Basicly I am trying to place a[0], b[0] in a seperate list
> IF a[2] and b[2] is present.
> I have tried sets, zip etc with no success.
> I am tackling Euler projects with Python 3.1, with minimal
> knowledge, and having to tackle the language as I progress.
> Enjoyable frustration  :)

I'm not clear on what your actual problem is, could you restate it?

It sounds like you want to copy the ith element out of a and b into
some other list- call it c- when the (i+2)th element meets some
condition. What's the condition?

Geremy Condra
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem...

2010-09-28 Thread Shashwat Anand
On Wed, Sep 29, 2010 at 12:14 AM, Rog  wrote:

> Hi all,
> Have been grappling with a list problem for hours...
> a = [2, 3, 4, 5,.]
> b = [4, 8, 2, 6,.]
> Basicly I am trying to place a[0], b[0] in a seperate list
> IF a[2] and b[2] is present.
>

You are not exactly clear with your problem statement.
Care to elaborate it more.


> I have tried sets, zip etc with no success.
> I am tackling Euler projects with Python 3.1, with minimal
> knowledge, and having to tackle the language as I progress.
> Enjoyable frustration  :)
>
> --
> Rog
> http://www.rog.pynguins.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
~l0nwlf
-- 
http://mail.python.org/mailman/listinfo/python-list


list problem...

2010-09-28 Thread Rog
Hi all,
Have been grappling with a list problem for hours...
a = [2, 3, 4, 5,.]
b = [4, 8, 2, 6,.]
Basicly I am trying to place a[0], b[0] in a seperate list
IF a[2] and b[2] is present.
I have tried sets, zip etc with no success.
I am tackling Euler projects with Python 3.1, with minimal
knowledge, and having to tackle the language as I progress.
Enjoyable frustration  :)

-- 
Rog
http://www.rog.pynguins.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple list problem that's defeating me!

2010-06-24 Thread Bruno Desthuilliers

Neil Webster a écrit :

Thanks for the help so far.

The background to the problem is that the lists come from reading a
dbf file.  The code that I am trying to write is to merge lines of the
dbf based on the first column.  So in my example there would be three
lines:
a 2 3 4
b 10 11 12
a 2 3 4

The expected output from the above example lines would be:
a 4 6 8
b 10 11 12

 ... and the lines are read as: [[a,2,3,4],[b,10,11,12], [a,2,3,4]]



If you don't care about the original ordering, the following code should 
do.


# 8<

def merge_rows(rows):
merged = dict()
for row in rows:
key, values = row[0], row[1:]
sums = merged.setdefault(key, [0, 0, 0])
for i, v in enumerate(values):
sums[i] += v

return [key] + value for key, value in merged.iteritems()]

import sys
def print_rows(rows, out=sys.stdout):
for row in rows:
print " ".join(map(str, row))

if __name__ == '__main__':
inputs = [['a',2,3,4],['b',10,11,12], ['a',2,3,4]]
expected = [['a',4,6,8],['b',10,11,12]]
print "inputs : "
print_rows(inputs)

outputs = merge_rows(inputs)
outputs.sort() # so we can do a simple equality test
assert outputs == expected, "Expected %s, got %s" % (
   expected, outputs
   )

print "outputs :"
print_rows(outputs)

# 8<



In response to not posting working code or actual inputs, ummm, that's
why I am asking the question here.


In this context, "working code" means "minimal code that a) can be 
executed and b) exhibits the problem you have, whatever the problem is". 
This code should include or be shipped with example input data and 
corresponding expected output data - as I did in the above code.



HTH
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple list problem that's defeating me!

2010-06-24 Thread Sion Arrowsmith
Mark Lawrence   wrote:
>On 22/06/2010 15:06, Neil Webster wrote:
>> I have a list of lists such as [[a,2,3,4],[b,10,11,12], [a,2,3,4]].  I
>> need to combine the two lists that have the same first character in
>> this example 'a'.  In reality there are 656 lists within the list.
>> [ ... ]
>My simplistic approach.
>
>Sort the list (this happens in place).
>Use the itertools groupby function to place everything together, see
>http://docs.python.org/library/itertools.html?highlight=groupby#itertools.groupby
>Combine the lists in the groups.

I suspect the following is a more efficient way of acheiving the grouping:

d = collections.defaultdict(list)
for a in L:
d[a[0]].append(a[1:])

-- 
\S

   under construction

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple list problem that's defeating me!

2010-06-24 Thread Neil Webster
Thanks for the help so far.

The background to the problem is that the lists come from reading a
dbf file.  The code that I am trying to write is to merge lines of the
dbf based on the first column.  So in my example there would be three
lines:
a 2 3 4
b 10 11 12
a 2 3 4

The expected output from the above example lines would be:
a 4 6 8
b 10 11 12

 ... and the lines are read as: [[a,2,3,4],[b,10,11,12], [a,2,3,4]]

In response to not posting working code or actual inputs, ummm, that's
why I am asking the question here.








On Jun 22, 4:38 pm, Bruno Desthuilliers  wrote:
> Neil Webster a crit :
>
> > Hi all,
>
> > I've got a simple problem but it's defeated me and I was wondering if
> > somebody could point out where I'm going wrong
>
> 1/ not posting working code (got a NameError)
> 2/ not posting the expected output
> 3/ not posting the actual output
>
> > or offer an alternative
> > solution to the problem?
>
> When you'll have fixed the 3 problems listed above !-)
>
> (snip broken code)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple list problem that's defeating me!

2010-06-22 Thread Bruno Desthuilliers

Neil Webster a écrit :

Hi all,

I've got a simple problem but it's defeated me and I was wondering if
somebody could point out where I'm going wrong


1/ not posting working code (got a NameError)
2/ not posting the expected output
3/ not posting the actual output


or offer an alternative
solution to the problem?


When you'll have fixed the 3 problems listed above !-)

(snip broken code)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple list problem that's defeating me!

2010-06-22 Thread Mark Lawrence

On 22/06/2010 15:06, Neil Webster wrote:

Hi all,

I've got a simple problem but it's defeated me and I was wondering if
somebody could point out where I'm going wrong or offer an alternative
solution to the problem?

I have a list of lists such as [[a,2,3,4],[b,10,11,12], [a,2,3,4]].  I
need to combine the two lists that have the same first character in
this example 'a'.  In reality there are 656 lists within the list.

My attempt so far is:
L = [[a,2,3,4],[b,10,11,12], [a,2,3,4]]
d = []
z = 1
while z<= len(L):
for a in L:
if L.count(a[0])>  1:
d.append(a[2:])

summed = [sum(pair) for pair in zip(d[0], d[1])]
z = z+1
print summed

Any pointers more than welcome.

Thanks all.



My simplistic approach.

Sort the list (this happens in place).
Use the itertools groupby function to place everything together, see
http://docs.python.org/library/itertools.html?highlight=groupby#itertools.groupby
Combine the lists in the groups.

HTH.

Mark Lawrence.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple list problem that's defeating me!

2010-06-22 Thread James Mills
On Wed, Jun 23, 2010 at 12:06 AM, Neil Webster  wrote:
> I've got a simple problem but it's defeated me and I was wondering if
> somebody could point out where I'm going wrong or offer an alternative
> solution to the problem?

Is this a hypothetical/mathematical problem of sorts ?
If so, do you have the actual problem description ?

It's often better to come up with a different (perhaps better)
solution without looking at someone else's :)

--james


-- 
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple list problem that's defeating me!

2010-06-22 Thread Xavier Ho
On 23 June 2010 00:06, Neil Webster  wrote:

> Hi all,
>
> I've got a simple problem but it's defeated me and I was wondering if
> somebody could point out where I'm going wrong or offer an alternative
> solution to the problem?
>
> I have a list of lists such as [[a,2,3,4],[b,10,11,12], [a,2,3,4]].  I
> need to combine the two lists that have the same first character in
> this example 'a'.  In reality there are 656 lists within the list.
>

Here's my take:

>>> input = [['a',2,3,4], ['b',10,11,12], ['a',2,3,4]]
>>> output = {}
>>> for i in input:
... output[i[0]] = output.get(i[0], 0) + sum(i[1:])
...
>>> output
{'a': 18, 'b': 33}

Note in your example, a and b are not defined, so I used a string instead.

Cheers,
Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Simple list problem that's defeating me!

2010-06-22 Thread Neil Webster
Hi all,

I've got a simple problem but it's defeated me and I was wondering if
somebody could point out where I'm going wrong or offer an alternative
solution to the problem?

I have a list of lists such as [[a,2,3,4],[b,10,11,12], [a,2,3,4]].  I
need to combine the two lists that have the same first character in
this example 'a'.  In reality there are 656 lists within the list.

My attempt so far is:
L = [[a,2,3,4],[b,10,11,12], [a,2,3,4]]
d = []
z = 1
while z <= len(L):
for a in L:
if L.count(a[0]) > 1:
d.append(a[2:])

summed = [sum(pair) for pair in zip(d[0], d[1])]
z = z+1
print summed

Any pointers more than welcome.

Thanks all.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested list problem - please...

2010-04-18 Thread Andreas Waldenburger
On Sat, 17 Apr 2010 13:31:54 -0700 Chris Rebert 
wrote:

> On Sat, Apr 17, 2010 at 12:40 PM, Martin Hvidberg
>  wrote:
> > I have this code, it builds up a data structure of nested lists,
> > and filling data in them. My problem is that it seems that one of
> > the lists SA[1] is not a list of unique instances but rather
> > individual links to the same variable. In the example below I
> > assign 'X' to what I intended to be the first Compounds Name. But
> > rather the 'X' goes into all the Compounds Name. I thought that the
> > [:] in SAdata.extend([CP[:]]) would ensure copies rather than links
> > to. What is going wrong?  
> 
> someList[:] only copies 1-level deep. If you have a list of lists,
> none of the inner lists will be copied; you'll get a new list of
> references to the same lists instead. I think your code assumes [:]
> copies lists recursively.

Expanding on that, Martin, I think "from copy import deepcopy" should
solve that problem.

/W

-- 
INVALID? DE!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested list problem - please...

2010-04-17 Thread Chris Rebert
On Sat, Apr 17, 2010 at 12:40 PM, Martin Hvidberg  wrote:
> I have this code, it builds up a data structure of nested lists, and filling 
> data in them.
> My problem is that it seems that one of the lists SA[1] is not a list of 
> unique instances but rather individual links to the same variable.
> In the example below I assign 'X' to what I intended to be the first 
> Compounds Name. But rather the 'X' goes into all the Compounds Name.
> I thought that the [:] in SAdata.extend([CP[:]]) would ensure copies rather 
> than links to.
> What is going wrong?

someList[:] only copies 1-level deep. If you have a list of lists,
none of the inner lists will be copied; you'll get a new list of
references to the same lists instead. I think your code assumes [:]
copies lists recursively.

Also, a.extend([b[:]]) is more efficiently and idiomatically written
as a.append(b[:])

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Nested list problem - please...

2010-04-17 Thread Martin Hvidberg
Dear list

I have this code, it builds up a data structure of nested lists, and filling 
data in them.
My problem is that it seems that one of the lists SA[1] is not a list of unique 
instances but rather individual links to the same variable.
In the example below I assign 'X' to what I intended to be the first Compounds 
Name. But rather the 'X' goes into all the Compounds Name.
I thought that the [:] in SAdata.extend([CP[:]]) would ensure copies rather 
than links to.
What is going wrong?

I include sample code, and I include the output it produces, and I manually 
inserted some line breaks and some indents, for readability.

:-) Martin

--- Code Start ---
LV = list() # LV for Lable Value pair
LV.extend(['lable','0'])

CP = list() # CP for ComPund
for i in range(0,5):
CP.extend([LV[:]]) # incl. 5 _copies_ of LV
CP[0][0] = 'Compound name'
CP[1][0] = 'Tgt'
CP[2][0] = 'Q1'
CP[3][0] = 'Q2'
CP[4][0] = 'Q3'

SA = list() # SA for SAmple
SAheader = list()
for i in range(0,3):
SAheader.extend([LV[:]])
SAheader[0][0] = 'fileinfo.txt'
SAheader[1][0] = 'Data file'
SAheader[2][0] = 'Sample name'
SA.extend([SAheader])
SAdata = list()
for i in range(0,2):
SAdata.extend([CP[:]]) 
SA.extend([SAdata])

print SA
SA[1][0][0][1] = 'X' 
print SA
--- Code End ---


[
[
['fileinfo.txt', '0'], 
['Data file', '0'], 
['Sample name', '0']
], 
[
[
['Compound name', 'X'], 
['Tgt', '0'], 
['Q1', '0'], 
['Q2', '0'], 
['Q3', '0']
], 
[
['Compound name', 'X'], 
['Tgt', '0'], 
['Q1', '0'], 
['Q2', '0'], 
['Q3', '0']
]
]
]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Problem

2008-12-09 Thread Robert Lehmann
On Tue, 09 Dec 2008 21:40:08 -0800, dongzhi wrote:

> I have one problem for List. Like that:
> 
> format='just "a" ""little"" test'
> part = format.split('"')
> print part
> 
> the result is : ['just ', 'a', ' ', '', 'little', '', ' test']
> 
> the list part have 7 element.
> 
> If I execute part[1], I have got  'a'. If I execute part[2], I have got
> ' '. But, if I execute part[1::2], I have got ['a', '', '']. I don't
> know why. Please tell me why.

You're slicing your list with the arguments "start at 1, stop at the end, 
using a step size of 2." It's basically the same as ``part[1], part[1+2], 
part[1+2+2], ...``. Perhaps you wanted to do ``part[1:3]`` (meaning 
"start at 1, stop before 3").

See the Python Reference for details.
http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-
list-tuple-buffer-xrange
http://docs.python.org/reference/expressions.html#id8

HTH,

-- 
Robert "Stargaming" Lehmann
--
http://mail.python.org/mailman/listinfo/python-list


Re: List Problem

2008-12-09 Thread dongzhi
On Dec 10, 2:00 pm, "James Mills" <[EMAIL PROTECTED]>
wrote:
> On Wed, Dec 10, 2008 at 3:40 PM, dongzhi <[EMAIL PROTECTED]> wrote:
> > If I execute part[1], I have got  'a'. If I execute part[2], I have
> > got ' '. But, if I execute part[1::2], I have got ['a', '', '']. I
> > don't know why. Please tell me why.
>
> Perhaps you meant:
>
> part[1:2]
>
> pydoc list
>
> This will tell you there are 3 arguments to __getslice__
> i, j, y
>
> Without doing any further reading I
> presume from my experience that
> this works much like range and xrange
> and that the 3rd parameter is the step
> size.
>
> Consider this:
>
>
>
> >>> x = [9, 1, 2, 3, 4]
> >>> x
> [9, 1, 2, 3, 4]
> >>> x[1:2]
> [1]
> >>> x[1::2]
> [1, 3]
> >>> x[1::1]
> [1, 2, 3, 4]
> >>> x[1::2]
> [1, 3]
> >>> x[1::3]
> [1, 4]
>
> cheers
> James
>
> --
> --
> -- "Problems are solved by method

Dear James Mills,

Thanks a lot. Now, I know the reason.

Best Regards,

Liu Ming
--
http://mail.python.org/mailman/listinfo/python-list


Re: List Problem

2008-12-09 Thread James Mills
On Wed, Dec 10, 2008 at 3:40 PM, dongzhi <[EMAIL PROTECTED]> wrote:
> If I execute part[1], I have got  'a'. If I execute part[2], I have
> got ' '. But, if I execute part[1::2], I have got ['a', '', '']. I
> don't know why. Please tell me why.

Perhaps you meant:

part[1:2]

pydoc list

This will tell you there are 3 arguments to __getslice__
i, j, y

Without doing any further reading I
presume from my experience that
this works much like range and xrange
and that the 3rd parameter is the step
size.

Consider this:

>>> x = [9, 1, 2, 3, 4]
>>> x
[9, 1, 2, 3, 4]
>>> x[1:2]
[1]
>>> x[1::2]
[1, 3]
>>> x[1::1]
[1, 2, 3, 4]
>>> x[1::2]
[1, 3]
>>> x[1::3]
[1, 4]
>>>

cheers
James

-- 
--
-- "Problems are solved by method
--
http://mail.python.org/mailman/listinfo/python-list


List Problem

2008-12-09 Thread dongzhi
Hi All,

I have one problem for List. Like that:

format='just "a" ""little"" test'
part = format.split('"')
print part

the result is : ['just ', 'a', ' ', '', 'little', '', ' test']

the list part have 7 element.

If I execute part[1], I have got  'a'. If I execute part[2], I have
got ' '. But, if I execute part[1::2], I have got ['a', '', '']. I
don't know why. Please tell me why.

Thanks.

Best Regards,

Liu Ming
--
http://mail.python.org/mailman/listinfo/python-list


Re: List problem

2007-12-16 Thread Mel
Alan Bromborsky wrote:
> I wish to create a list of empty lists and then put something in one of 
> the empty lists.  Below is what I tried, but instead of appending 1 to 
> a[2] it was appended to all the sub-lists in a.  What am I doing wrong?
> 
> a = 6*[[]]
>  >>> a
> [[], [], [], [], [], []]
>  >>> a[2].append(1)
>  >>> a
> [[1], [1], [1], [1], [1], [1]]
>  >>> 

What you've done is equivalent to

x = []
a = [x, x, x, x, x, x]
del x

An idiom for what you want is

a = [[] for y in xrange (6)]

which will populate a with 6 distinct empty lists.

Cheers, Mel.
-- 
http://mail.python.org/mailman/listinfo/python-list


List problem

2007-12-16 Thread Alan Bromborsky
I wish to create a list of empty lists and then put something in one of 
the empty lists.  Below is what I tried, but instead of appending 1 to 
a[2] it was appended to all the sub-lists in a.  What am I doing wrong?

 a = 6*[[]]
 >>> a
[[], [], [], [], [], []]
 >>> a[2].append(1)
 >>> a
[[1], [1], [1], [1], [1], [1]]
 >>>  
-- 
http://mail.python.org/mailman/listinfo/python-list


[python-list] Problem with SQLObject

2007-10-25 Thread Guillermo Heizenreder
I'm creating one aplicattion and I use SQLObject, but I have a little
problem, when I try to create one table my aplicattion crash! :(
Let me show you:

[EMAIL PROTECTED]:~/Proyectos/ghhp/lib$ python
Python 2.4.4 (#2, Apr  5 2007, 20:11:18)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sqlobject import *
>>> from connection import conn
>>> class User(SQLObject):
... _connection = conn
... user_name = StringCol(length=14, unique=True)
... un_pass = StringCol(length=10)
...
>>> User.createTable()
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/lib/python2.4/site-packages/sqlobject/main.py", line 1332,
in createTable
conn.createTable(cls)
  File "/usr/lib/python2.4/site-packages/sqlobject/dbconnection.py",
line 528, in createTable
self.query(self.createTableSQL(soClass))
  File "/usr/lib/python2.4/site-packages/sqlobject/dbconnection.py",
line 307, in query
return self._runWithConnection(self._query, s)
  File "/usr/lib/python2.4/site-packages/sqlobject/dbconnection.py",
line 219, in _runWithConnection
conn = self.getConnection()
  File "/usr/lib/python2.4/site-packages/sqlobject/dbconnection.py",
line 230, in getConnection
conn = self.makeConnection()
  File
"/usr/lib/python2.4/site-packages/sqlobject/mysql/mysqlconnection.py",
line 51, in makeConnection
db=self.db, user=self.user, passwd=self.password, **self.kw)
  File "/usr/lib/python2.4/site-packages/MySQLdb/__init__.py", line 75,
in Connect
return Connection(*args, **kwargs)
  File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line
164, in __init__
super(Connection, self).__init__(*args, **kwargs2)
TypeError: an integer is required
>>>

I can't find the mistake. 
First I thought that not create correctly the conection to mysql, but
testening show me this:

>>> User._connection

>>>

Saw it seems that it works.
Please cant you help me.
Thank's and regards

-- 
+-
| Heizenreder Guillermo 
| http://gheize.wordpress.com/
| http://code.google.com/u/gheize/
| http://tipslinux.blogspot.com/
+-

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List problem

2006-08-25 Thread Georg Brandl
[EMAIL PROTECTED] wrote:
> For example i write the following code in the Python command line;
> 
list = ['One,Two,Three,Four']
> 
> Then enter this command, which will then return the following;
> 
> ['One,Two,Three,Four']

This is already wrong. Assignments do not return anything.

Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List problem

2006-08-24 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> For example i write the following code in the Python command line;
> 
 list = ['One,Two,Three,Four']
> 
> Then enter this command, which will then return the following;
> 
> ['One,Two,Three,Four']
> 
> 
> Now the problem, reading through the Python tutorial's, it describe's
> that list's can sliced, concatenated and so on etc
> 
> So i write the following
> 
 list[1:] + ['Five']
> 
> Then the error returned is that 'str' and 'list' could not be
> concatenated which is where it baffles me. I'm understanding that this
> mean's that the string 'Five' could not be joined onto the list, as i
> havn't defined it in the array. Viewing the Python tutrial they have
> the following, and working code;
> 
 a[:2] + ['bacon', 2*2]
> ['spam', 'eggs', 'bacon', 4]
> 
> How can they have the string 'bacon' and have it returned with no
> error?
> 
Your error message doesn't match your command.  Now if you
typed:

list[0]+['Five']

that gives you the error you showed.

What you meant to type was:

l = ['One','Two','Three','Four']

This is a list of four strings, what you entered was a list of one
string.

NOTE never call a variable 'list' as it will mask the built-in list
method (same goes for str, tuple, int, float, etc).

-Larry Bates

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List problem

2006-08-24 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> For example i write the following code in the Python command line;
> 
 list = ['One,Two,Three,Four']
> 
> Then enter this command, which will then return the following;
> 
> ['One,Two,Three,Four']
> 
> 
> Now the problem, reading through the Python tutorial's, it describe's
> that list's can sliced, concatenated and so on etc
> 
> So i write the following
> 
 list[1:] + ['Five']
> 
> Then the error returned is that 'str' and 'list' could not be
> concatenated which is where it baffles me.

if you got that error, you clearly didn't type what you say you typed:

 >>> list = ['One,Two,Three,Four']
 >>> list
['One,Two,Three,Four']
 >>> list[1:] + ['Five']
['Five']

(note that the first list contains a single string; if you want to put 
multiple strings in a list, you need to be more careful with where you 
put the quotes.)



-- 
http://mail.python.org/mailman/listinfo/python-list


List problem

2006-08-24 Thread kevndcks
For example i write the following code in the Python command line;

>>>list = ['One,Two,Three,Four']

Then enter this command, which will then return the following;

['One,Two,Three,Four']


Now the problem, reading through the Python tutorial's, it describe's
that list's can sliced, concatenated and so on etc

So i write the following

>>>list[1:] + ['Five']

Then the error returned is that 'str' and 'list' could not be
concatenated which is where it baffles me. I'm understanding that this
mean's that the string 'Five' could not be joined onto the list, as i
havn't defined it in the array. Viewing the Python tutrial they have
the following, and working code;

>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]

How can they have the string 'bacon' and have it returned with no
error?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to display name of elements in list? PROBLEM SOLVED.

2006-07-27 Thread cz

[EMAIL PROTECTED] wrote:
> It looks like the PyTensor object *should* have .xx, .xy, etc
> properties, but they may be accessible through a matrix, i.e. .t(i,j)


Thanks to all of you for your help!
The solution is easy: The tensor components have labels t11, t12,...
Good guess ruibalp!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-26 Thread placid
Thank you all for the replies, i now have a better solution.


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-26 Thread Paul Rubin
"placid" <[EMAIL PROTECTED]> writes:
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']
> 
> the second list contains strings that are identical to the first list,
> so lets say the second list contains the following
> 
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']

I think you meant list2 for the second one.  So:


import re

list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']
list2 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']

def num(s):
   # get the number out of one of the strings 
   # (throw exception if no number is there)
   digits = re.search('\d+$', s)
   return int(digits.group(0))

def get_lowest_unused(list1, list2):
   prev = 0
   for n in sorted(set(map(num,list1+list2))):
   if n != prev+1:
  return prev+1
   prev = n

print get_lowest_unused(list1, list2)

You could do all this with iterators and save a little memory, but
that's more confusing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-26 Thread Gerard Flanagan

Gerard Flanagan wrote:
> placid wrote:
> > Hi all,
> >
> > I have two lists that contain strings in the form string + number for
> > example
> >
> > >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']
> >
> > the second list contains strings that are identical to the first list,
> > so lets say the second list contains the following
> >
> > >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']
> >
> > and now what ive been trying to do is find the first string that is
> > available,
> > i.e a string that is in neither of the two lists so the following code
> > should only print XXX4 then return.
> >
> > for i in xrange(1,10):
> > numpart = str(1) + str("%04i" %i)
> > str = "XXX" + numpart
> >
> >   for list1_elm in list1:
> >   if list1_elm == str:
> >break
> >   else:
> >for list2_elm in list2:
> >if list2_elm == str:
> >   break
> >else:
> >   print str
> >   return
> >
> > Cheer
>
> I don't know how close the following is to what you want ( or how
> efficient etc...).  If both lists are the same up to a certain point,
> then the first function should do, if not, try the second function.
>
> Gerard
>
> from itertools import izip, dropwhile
>
> def get_first_missing1( seq1, seq2 ):
> i = int( seq1[0][-1] )
> for x1, x2 in izip( seq1, seq2 ):
> if int(x1[-1]) != i and int(x2[-1]) != i:
> return x1[:-1] + str(i)
> i += 1
> return -1
>
> def get_first_missing2( seq1, seq2 ):
> i = int( seq1[0][-1] )
> j = int( seq2[0][-1] )
> if j < i:
> seq1, seq2 = seq2, seq1
> i, j = j, i
> return get_first_missing1( list(dropwhile(lambda s: int(s[-1]) < j,
> seq1)), seq2 )
>
> L1 = [ 'XXX1', 'XXX2', 'XXX3', 'XXX5']
> L2 = [ 'YYY1', 'YYY2', 'YYY3', 'YYY6']
>
> print get_first_missing1(L1, L2)
> print get_first_missing2(L1, L2)
> 'XXX4'
> 'XXX4'

ehm...a bit limited in what it will handle, now that I look at it! like
more than ten items in a list - '11'[-1] == '1'...no time to test
further, sorry:(

Gerard

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-26 Thread Gerard Flanagan

placid wrote:
> Hi all,
>
> I have two lists that contain strings in the form string + number for
> example
>
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']
>
> the second list contains strings that are identical to the first list,
> so lets say the second list contains the following
>
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']
>
> and now what ive been trying to do is find the first string that is
> available,
> i.e a string that is in neither of the two lists so the following code
> should only print XXX4 then return.
>
> for i in xrange(1,10):
> numpart = str(1) + str("%04i" %i)
> str = "XXX" + numpart
>
>   for list1_elm in list1:
>   if list1_elm == str:
>break
>   else:
>for list2_elm in list2:
>if list2_elm == str:
>   break
>else:
>   print str
>   return
>
> Cheer

I don't know how close the following is to what you want ( or how
efficient etc...).  If both lists are the same up to a certain point,
then the first function should do, if not, try the second function.

Gerard

from itertools import izip, dropwhile

def get_first_missing1( seq1, seq2 ):
i = int( seq1[0][-1] )
for x1, x2 in izip( seq1, seq2 ):
if int(x1[-1]) != i and int(x2[-1]) != i:
return x1[:-1] + str(i)
i += 1
return -1

def get_first_missing2( seq1, seq2 ):
i = int( seq1[0][-1] )
j = int( seq2[0][-1] )
if j < i:
seq1, seq2 = seq2, seq1
i, j = j, i
return get_first_missing1( list(dropwhile(lambda s: int(s[-1]) < j,
seq1)), seq2 )

L1 = [ 'XXX1', 'XXX2', 'XXX3', 'XXX5']
L2 = [ 'YYY1', 'YYY2', 'YYY3', 'YYY6']

print get_first_missing1(L1, L2)
print get_first_missing2(L1, L2)
'XXX4'
'XXX4'

L1 = [ 'XXX1', 'XXX2', 'XXX3', 'XXX5']
L2 = [ 'YYY2', 'YYY3', 'YYY5', 'YYY6']

print get_first_missing1(L1, L2)
print get_first_missing2(L1, L2)
'XXX4'
'XXX4'

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-26 Thread Simon Forman
placid wrote:
>
> But there may be other characters before XXX (which XXX is constant). A
> better example would be, that string s is like a file name and the
> characters before it are the absolute path, where the strings in the
> first list can have a different absolute path then the second list
> entries. But the filenames are always exact. So you need to split the
> entries bases on "\\" (windows machine) and match on this ?
>
>
> Cheers

If you're actually working with filenames and paths then you should use
os.path.basename() to get just the filename parts of the paths.

test = set(map(os.path.basename, list1))
test |= set(map(os.path.basename, list2))

(Note: I *was* being stupid last night, the + operator doesn't work for
sets. You want to use | )

Peace,
~Simon

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-26 Thread zutesmog

placid wrote:
> Hi all,
>
> I have two lists that contain strings in the form string + number for
> example
>
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']
>
> the second list contains strings that are identical to the first list,
> so lets say the second list contains the following
>
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']
>
> and now what ive been trying to do is find the first string that is
> available,
> i.e a string that is in neither of the two lists so the following code
> should only print XXX4 then return.
>
> for i in xrange(1,10):
> numpart = str(1) + str("%04i" %i)
> str = "XXX" + numpart
>
>   for list1_elm in list1:
>   if list1_elm == str:
>break
>   else:
>for list2_elm in list2:
>if list2_elm == str:
>   break
>else:
>   print str
>   return
>
> Cheer

Just a thought

I would probably use sets and see if the value that you are looking for
using the
union of the two lists. (Yes it won't scale to really big lists)
for instance if you do the following
set1 = set(list1)
set2 = set(list2)


you can then do a single check

if "XXX%d" % i not in set1.union(set2):  # or set1 | set2
 # do something

Rgds

Tim

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-26 Thread bearophileHUGS
placid:

This may be a solution:

l1 = ['acXXX1', 'XXX2', 'wXXX3', 'kXXX5']
l2 = [ 'bXXX1', 'xXXX2', 'efXXX3', 'yXXX6', 'zZZZ9']

import re
findnum = re.compile(r"[0-9]+$")
s1 = set(int(findnum.search(el).group()) for el in l1)
s2 = set(int(findnum.search(el).group()) for el in l2)
nmax = max(max(s1), max(s2))
# XXXnmax is surely unavailable
missing = set(range(1, nmax)) - s1 - s2
print ["XXX%d" % i for i in sorted(missing)]

# Output: ['XXX4', 'XXX7', 'XXX8']

If you need more speed you can replace some of those sets (like the
range one) with fors.

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-25 Thread Simon Forman
placid wrote:
> Simon Forman wrote:
> > placid wrote:
> > > Hi all,
> > >
> > > I have two lists that contain strings in the form string + number for
> > > example
> > >
> > > >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']
> > >
> > > the second list contains strings that are identical to the first list,
> > > so lets say the second list contains the following
> > >
> > > >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']
> > >
> > > and now what ive been trying to do is find the first string that is
> > > available,
> > > i.e a string that is in neither of the two lists so the following code
> > > should only print XXX4 then return.
> > >
> > > for i in xrange(1,10):
> > > numpart = str(1) + str("%04i" %i)
> > > str = "XXX" + numpart
> > >
> > >   for list1_elm in list1:
> > >   if list1_elm == str:
> > >break
> > >   else:
> > >for list2_elm in list2:
> > >if list2_elm == str:
> > >   break
> > >else:
> > >   print str
> > >   return
> > >
> > > Cheer
> >
> > Well first off, don't use 'str' for a variable name.
> >
> > Second, "%04i" % i creates a string, don't call str() on it.
> >
> > Third, str(1) will always be "1" so just add that to your format string
> > already "1%04i" % i
> >
>
> thanks for the tips
>
> > (And if the "XXX" part is also constant then add that too: "XXX1%04i" %
> > i)
> >
> > Finally, you can say:
> >
> > for i in xrange(1,10):
> > s = "XXX1%04i" % i
> > if s not in list1 and s not in list2:
> > print s
> >
>
> But there may be other characters before XXX (which XXX is constant). A
> better example would be, that string s is like a file name and the
> characters before it are the absolute path, where the strings in the
> first list can have a different absolute path then the second list
> entries. But the filenames are always exact. So you need to split the
> entries bases on "\\" (windows machine) and match on this ?
>
>
> Cheers

hmm, a slightly different problem than your OP.

Yeah, I would build a new list (or set) from the contents of BOTH lists
with the prefixes stripped off and test your target string against
that.  You might also be able to do something with the endswith()
method of strings.

test = set(n[3:] for n in list1) + set(n[3:] for n in list2)

if s not in test: print s


It's late though, so I may be being stupid.  ;-)

Peace,
~Simon

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-25 Thread placid

Simon Forman wrote:
> placid wrote:
> > Hi all,
> >
> > I have two lists that contain strings in the form string + number for
> > example
> >
> > >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']
> >
> > the second list contains strings that are identical to the first list,
> > so lets say the second list contains the following
> >
> > >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']
> >
> > and now what ive been trying to do is find the first string that is
> > available,
> > i.e a string that is in neither of the two lists so the following code
> > should only print XXX4 then return.
> >
> > for i in xrange(1,10):
> > numpart = str(1) + str("%04i" %i)
> > str = "XXX" + numpart
> >
> >   for list1_elm in list1:
> >   if list1_elm == str:
> >break
> >   else:
> >for list2_elm in list2:
> >if list2_elm == str:
> >   break
> >else:
> >   print str
> >   return
> >
> > Cheer
>
> Well first off, don't use 'str' for a variable name.
>
> Second, "%04i" % i creates a string, don't call str() on it.
>
> Third, str(1) will always be "1" so just add that to your format string
> already "1%04i" % i
>

thanks for the tips

> (And if the "XXX" part is also constant then add that too: "XXX1%04i" %
> i)
>
> Finally, you can say:
>
> for i in xrange(1,10):
> s = "XXX1%04i" % i
> if s not in list1 and s not in list2:
> print s
>

But there may be other characters before XXX (which XXX is constant). A
better example would be, that string s is like a file name and the
characters before it are the absolute path, where the strings in the
first list can have a different absolute path then the second list
entries. But the filenames are always exact. So you need to split the
entries bases on "\\" (windows machine) and match on this ?


Cheers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-25 Thread Simon Forman
Simon Forman wrote:
> Finally, you can say:
>
> for i in xrange(1,10):
> s = "XXX1%04i" % i
> if s not in list1 and s not in list2:
> print s
>
> HTH,
> ~Simon

D'oh!  Forgot to break.

for i in xrange(1,10):
s = "XXX1%04i" % i
if s not in list1 and s not in list2:
print s
break

Peace,
~Simon

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem

2006-07-25 Thread Simon Forman
placid wrote:
> Hi all,
>
> I have two lists that contain strings in the form string + number for
> example
>
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']
>
> the second list contains strings that are identical to the first list,
> so lets say the second list contains the following
>
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']
>
> and now what ive been trying to do is find the first string that is
> available,
> i.e a string that is in neither of the two lists so the following code
> should only print XXX4 then return.
>
> for i in xrange(1,10):
> numpart = str(1) + str("%04i" %i)
> str = "XXX" + numpart
>
>   for list1_elm in list1:
>   if list1_elm == str:
>break
>   else:
>for list2_elm in list2:
>if list2_elm == str:
>   break
>else:
>   print str
>   return
>
> Cheer

Well first off, don't use 'str' for a variable name.

Second, "%04i" % i creates a string, don't call str() on it.

Third, str(1) will always be "1" so just add that to your format string
already "1%04i" % i

(And if the "XXX" part is also constant then add that too: "XXX1%04i" %
i)

Finally, you can say:

for i in xrange(1,10):
s = "XXX1%04i" % i
if s not in list1 and s not in list2:
print s

HTH,
~Simon

-- 
http://mail.python.org/mailman/listinfo/python-list


list problem

2006-07-25 Thread placid
Hi all,

I have two lists that contain strings in the form string + number for
example

>>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']

the second list contains strings that are identical to the first list,
so lets say the second list contains the following

>>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']

and now what ive been trying to do is find the first string that is
available,
i.e a string that is in neither of the two lists so the following code
should only print XXX4 then return.

for i in xrange(1,10):
numpart = str(1) + str("%04i" %i)
str = "XXX" + numpart

  for list1_elm in list1:
  if list1_elm == str:
   break
  else:
   for list2_elm in list2:
   if list2_elm == str:
  break
   else:
  print str
  return

Cheer

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem 4 newbie

2006-06-26 Thread manstey
Thanks very much. Deepcopy works fine, as does reversed(b). I thought I
needed the index number but I didn't.


Duncan Booth wrote:

> manstey wrote:
>
> > for index in reversed(range(0,len(a)-1)):
> >if '75' in b[index][1]:
> >   b[index][1].remove('75')
> >   b[index][1].append('99')
> >
>
> What on earth is all that messing around in the for loop intended to do? If
> you want a range from len(a)-2 to 0 inclusive then just do it in range
> directly (and did you really mean not to look at the last element?), if you
> actually just wanted to iterate through b in reverse, then just iterate
> through b in reverse:
>
> b = copy.deepcopy(a)
> for element in reversed(b):
>if '75' in element[1]:
>   element[1].remove('75')
>   element[1].append('99')

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem 4 newbie

2006-06-26 Thread Duncan Booth
manstey wrote:

> for index in reversed(range(0,len(a)-1)):
>if '75' in b[index][1]:
>   b[index][1].remove('75')
>   b[index][1].append('99')
> 

What on earth is all that messing around in the for loop intended to do? If 
you want a range from len(a)-2 to 0 inclusive then just do it in range 
directly (and did you really mean not to look at the last element?), if you 
actually just wanted to iterate through b in reverse, then just iterate 
through b in reverse:

b = copy.deepcopy(a)
for element in reversed(b):
   if '75' in element[1]:
  element[1].remove('75')
  element[1].append('99')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list problem 4 newbie

2006-06-25 Thread vaibhav
Hi,
if u check the id's of a and b lists and also its elements, you will
obeserve that the id's of a and b have changed  but id's of their
elements have not changed.
 If you make a deep copy of the list a and then make your changes in
that list, it shud work.  this can be done using the copy module.

hope that helps,
vaibhav

>>> id(a)
-1208622388
>>> id(b)
-1208622324

>>> for el in a:
... print id(el)
...
-1208622836
-1208622708
-1208622772
-1208622420

>>> for el in b:
... print id(el)
...
-1208622836
-1208622708
-1208622772
-1208622420

>>> import copy
>>> c = copy.deepcopy(a)
>>> id(c)
-1208464564

>>> for el in c:
... print id(el)
...
-1208465172
-1208464276
-1208464180
-1208463988

-- 
http://mail.python.org/mailman/listinfo/python-list


list problem 4 newbie

2006-06-25 Thread manstey
I can't figure out why my code is not working. I thought I had the list
copied correctly:

Here is my code:



a=[[u'HF', []], [u')F', [u'75']], [u'RE', []], [u'C', []]]
b=a[:]

for index in reversed(range(0,len(a)-1)):
   if '75' in b[index][1]:
  b[index][1].remove('75')
  b[index][1].append('99')

print a,'\n',b



but when it finishes, I get

[[u'HF', []], [u')F', ['99']], [u'RE', []], [u'C', []]]
[[u'HF', []], [u')F', ['99']], [u'RE', []], [u'C', []]]

instead of the desired:

[[u'HF', []], [u')F', ['75']], [u'RE', []], [u'C', []]]
[[u'HF', []], [u')F', ['99']], [u'RE', []], [u'C', []]]

why is this?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping list problem

2005-08-17 Thread bruno modulix
Fredrik Lundh wrote:
> Jon Bowlas wrote:
(snip)

>>But I get the following error- Line 5: Yield statements are not allowed.
> 
> 
> umm.  I might be missing something, but I cannot find any trace of that
> error message in the Python interpreter source code.  it doesn't even look
> like a Python traceback.  did you perhaps forget to tell us that you're using
> some fancy web framework that uses Python in its own idiosyncratic way?

Some fancy web framework named Zope, I guess...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: looping list problem

2005-08-16 Thread Jon Bowlas
Many thanks for your help, worked a treat

Jon

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Peter
Otten
Sent: 16 August 2005 17:25
To: python-list@python.org
Subject: RE: looping list problem

Jon Bowlas wrote:

> Incidentally I'm doing this in zope.

Many posters (including me) in this newsgroup don't do zope, so your best
option is to ask on a zope-related mailing list.

> I was hoping that this would loop through the elements in the list
> returned by the hiddens function comparing them with the id of the current
> value of c (bert) and if they are the same then it should ignore it and
> move onto the next one, but it doesn't seem to do anything.

> Ok, so I've adapted my script calling it a hiddens() function and included
> it inside my get_tree_html function which creates my navigation:
> 
> pub = context.get_publication()
> obj = context.aq_inner
> fpath = context.getPhysicalPath()
> 
> def hiddens():
> attobject = context.get_attobject()
> navstring = context.get_uclattribute(attobject, 'ucl_navhide')
> return navstring.split(' ')
> 
> def get_tree_html(node, endobj):
> tree = ''
> endpath = endobj.getPhysicalPath()
> for c in node.get_ordered_publishables():
> if not c.is_published():
> continue
> bert=c.getId();
> if bert=="index_right":
> continue
> if bert=="images":
> continue
> # this is where I loop through he elements returned by my hiddens
> # function, comparing them with the value of bert

Replace these lines

> for element in hiddens():
>   if element==bert:
>   continue # with the next hidden element

with

  if bert in hiddens():
  continue # with the next publishable c

A 'continue' statement only affects the innermost loop, and as you don't
have any code that follows it in the for-element-loop it didn't have any
effect.

Peter

-- 
http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: looping list problem

2005-08-16 Thread Peter Otten
Jon Bowlas wrote:

> Incidentally I'm doing this in zope.

Many posters (including me) in this newsgroup don't do zope, so your best
option is to ask on a zope-related mailing list.

> I was hoping that this would loop through the elements in the list
> returned by the hiddens function comparing them with the id of the current
> value of c (bert) and if they are the same then it should ignore it and
> move onto the next one, but it doesn't seem to do anything.

> Ok, so I've adapted my script calling it a hiddens() function and included
> it inside my get_tree_html function which creates my navigation:
> 
> pub = context.get_publication()
> obj = context.aq_inner
> fpath = context.getPhysicalPath()
> 
> def hiddens():
> attobject = context.get_attobject()
> navstring = context.get_uclattribute(attobject, 'ucl_navhide')
> return navstring.split(' ')
> 
> def get_tree_html(node, endobj):
> tree = ''
> endpath = endobj.getPhysicalPath()
> for c in node.get_ordered_publishables():
> if not c.is_published():
> continue
> bert=c.getId();
> if bert=="index_right":
> continue
> if bert=="images":
> continue
> # this is where I loop through he elements returned by my hiddens
> # function, comparing them with the value of bert

Replace these lines

> for element in hiddens():
>   if element==bert:
>   continue # with the next hidden element

with

  if bert in hiddens():
  continue # with the next publishable c

A 'continue' statement only affects the innermost loop, and as you don't
have any code that follows it in the for-element-loop it didn't have any
effect.

Peter

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: looping list problem

2005-08-16 Thread Jon Bowlas
Ok, so I've adapted my script calling it a hiddens() function and included
it inside my get_tree_html function which creates my navigation:

pub = context.get_publication()
obj = context.aq_inner
fpath = context.getPhysicalPath()

def hiddens():
attobject = context.get_attobject()
navstring = context.get_uclattribute(attobject, 'ucl_navhide')
return navstring.split(' ')

def get_tree_html(node, endobj):
tree = ''
endpath = endobj.getPhysicalPath()
for c in node.get_ordered_publishables():
if not c.is_published():
continue
bert=c.getId();
if bert=="index_right":
continue
if bert=="images":
continue
# this is where I loop through he elements returned by my hiddens function,
comparing them with the value of bert
for element in hiddens():
if element==bert:
   continue
ppath = c.aq_parent.getPhysicalPath()
if not fpath[:len(ppath)] == ppath:
continue
if len(ppath) - 1 > len(endpath):
continue
html_si = '\n%(title)s'
cl = 'space'
if c == endobj:
cl = 'space'
si = {'url': c.absolute_url(),
'class': cl,
'title': c.getProperty('short_title') or
c.get_title()}
tree += html_si % si
if (c.get_container() == c and
c.is_transparent()):
tree += get_tree_html(c, endobj)
tree += '\n'
if tree:

tree = '  %s \n'  %tree
return tree

top_class = 'space'
if pub.aq_inner == obj:
top_class = 'space'
treetop = '\n\n' 

return '%s%s' % (treetop, get_tree_html(pub, obj)[19:])

I was hoping that this would loop through the elements in the list returned
by the hiddens function comparing them with the id of the current value of c
(bert) and if they are the same then it should ignore it and move onto the
next one, but it doesn't seem to do anything.

Any help would be appreciated.

Incidentally I'm doing this in zope.

Jon




-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Peter
Otten
Sent: 16 August 2005 14:41
To: python-list@python.org
Subject: RE: looping list problem

Jon Bowlas wrote:

> Ok so I changed it to this:
> 
> attobject = context.get_attobject()
> navstring = context.get_uclattribute(attobject, 'ucl_navhide')
> hiddennavelements = navstring.split(' ')
> for hiddennavelement in hiddennavelements:
> yield hiddennavelements
> 
> But I get the following error- Line 5: Yield statements are not allowed.

Please show us some more code -- especially the function containing and the
function calling the above chunk.

Generally speaking, a function terminates when execution reaches the first
return statement, e. g.

def f():
for i in 1, 2, 3:
return i

will always return 1. A generator, on the other hand,

def g():
for i in 1, 2, 3:
 yield i

will yield 1, 2, and 3, but the calling code then needs itself a for loop:

for i in g():
# do something with i

My guess would be that you should either modify your for loop to

> attobject = context.get_attobject()
> navstring = context.get_uclattribute(attobject, 'ucl_navhide')
> hiddennavelements = navstring.split(' ')
for hiddennavelement in hiddennavelements:
   # do something with hiddennavelement

or just return all elements at once

def some_func():
# ...
attobject = context.get_attobject()
navstring = context.get_uclattribute(attobject, 'ucl_navhide')
return navstring.split(' ')

and then operate on the items in the hiddennavelements list in the calling
code:

for element in some_func():
# do something with element

Peter










-- 
http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: looping list problem

2005-08-16 Thread Peter Otten
Jon Bowlas wrote:

> Ok so I changed it to this:
> 
> attobject = context.get_attobject()
> navstring = context.get_uclattribute(attobject, 'ucl_navhide')
> hiddennavelements = navstring.split(' ')
> for hiddennavelement in hiddennavelements:
> yield hiddennavelements
> 
> But I get the following error- Line 5: Yield statements are not allowed.

Please show us some more code -- especially the function containing and the
function calling the above chunk.

Generally speaking, a function terminates when execution reaches the first
return statement, e. g.

def f():
for i in 1, 2, 3:
return i

will always return 1. A generator, on the other hand,

def g():
for i in 1, 2, 3:
 yield i

will yield 1, 2, and 3, but the calling code then needs itself a for loop:

for i in g():
# do something with i

My guess would be that you should either modify your for loop to

> attobject = context.get_attobject()
> navstring = context.get_uclattribute(attobject, 'ucl_navhide')
> hiddennavelements = navstring.split(' ')
for hiddennavelement in hiddennavelements:
   # do something with hiddennavelement

or just return all elements at once

def some_func():
# ...
attobject = context.get_attobject()
navstring = context.get_uclattribute(attobject, 'ucl_navhide')
return navstring.split(' ')

and then operate on the items in the hiddennavelements list in the calling
code:

for element in some_func():
# do something with element

Peter










-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping list problem

2005-08-16 Thread Peter Hansen
Jon Bowlas wrote:
> Ok so I changed it to this: 
> 
> attobject = context.get_attobject()
> navstring = context.get_uclattribute(attobject, 'ucl_navhide')
> hiddennavelements = navstring.split(' ')
> for hiddennavelement in hiddennavelements:
> yield hiddennavelements
> 
> But I get the following error- Line 5: Yield statements are not allowed.

Please post the full traceback (cut and paste).  Don't just retype the 
error message like that.

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


Re: looping list problem

2005-08-16 Thread Fredrik Lundh
Jon Bowlas wrote:

> Ok so I changed it to this:
>
> attobject = context.get_attobject()
> navstring = context.get_uclattribute(attobject, 'ucl_navhide')
> hiddennavelements = navstring.split(' ')
> for hiddennavelement in hiddennavelements:
>yield hiddennavelements
>
> But I get the following error- Line 5: Yield statements are not allowed.

umm.  I might be missing something, but I cannot find any trace of that
error message in the Python interpreter source code.  it doesn't even look
like a Python traceback.  did you perhaps forget to tell us that you're using
some fancy web framework that uses Python in its own idiosyncratic way?

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping list problem

2005-08-16 Thread Paul McGuire
Well, you are returning prematurely from a for loop, so that is why you
are only getting the first value.  Its just like:

for i in range(100):
return i

It doesn't matter how big the range is you are iterating over, you'll
return on the first element and that's it.

If what you want is the list, then return the list:

hiddennavelements = navstring.split(' ')
return hiddennavelements

I think Fredrik Lundh was trying to accommodate your mixed thinking by
assuming your code was from a generator function.  With a generator,
you *can* return successive elements of a list, but you use the 'yield'
keyword instead of 'return', and repeated calls to the generator return
each successive value.

-- Paul

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: looping list problem

2005-08-16 Thread Jon Bowlas
Ok so I changed it to this: 

attobject = context.get_attobject()
navstring = context.get_uclattribute(attobject, 'ucl_navhide')
hiddennavelements = navstring.split(' ')
for hiddennavelement in hiddennavelements:
yield hiddennavelements

But I get the following error- Line 5: Yield statements are not allowed.

Any ideas

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Fredrik Lundh
Sent: 16 August 2005 13:44
To: python-list@python.org
Subject: Re: looping list problem

Jon Bowlas wrote:

> attobject = context.get_attobject()
> navstring = context.get_uclattribute(attobject, 'ucl_navhide')
> hiddennavelements = navstring.split(' ')
> for hiddennavelement in hiddennavelements:
>return hiddennavelement
>
> So the script 'get_attobject' basically looks for an instance of the
> attributes object in the current folder, if it doesn't locate one then it
> uses acquisition to find one in a parent folder. The script
> 'get_uclattribute' then gets the nodeValues of the requested node. In this
> instance its ucl_navhide, then I split the 'navstring' string at the
spaces
> and attempt the for-loop to output each of the values.
>
> Unfortunately it appears I am unable to loop through each of the list
items
> in hiddennavelements, as it only returns the first value & will not
repeat.

did you perhaps mean to use "yield" instead of "return" ?

 



-- 
http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping list problem

2005-08-16 Thread Fredrik Lundh
Jon Bowlas wrote:

> attobject = context.get_attobject()
> navstring = context.get_uclattribute(attobject, 'ucl_navhide')
> hiddennavelements = navstring.split(' ')
> for hiddennavelement in hiddennavelements:
>return hiddennavelement
>
> So the script 'get_attobject' basically looks for an instance of the
> attributes object in the current folder, if it doesn't locate one then it
> uses acquisition to find one in a parent folder. The script
> 'get_uclattribute' then gets the nodeValues of the requested node. In this
> instance its ucl_navhide, then I split the 'navstring' string at the spaces
> and attempt the for-loop to output each of the values.
>
> Unfortunately it appears I am unable to loop through each of the list items
> in hiddennavelements, as it only returns the first value & will not repeat.

did you perhaps mean to use "yield" instead of "return" ?

 



-- 
http://mail.python.org/mailman/listinfo/python-list


looping list problem

2005-08-16 Thread Jon Bowlas
HI all,

I'm fairly new to python and programming in general so I was hoping someone
here may be able to help me. Let me explain what the problem I'm having is:

I am trying to parse the XML of an attributes object I created, this object
has the structure outlined below. Everything is ok on the parsing front
until I try to get the values in ucl_navhide (StringField); these are
basically the id's of objects I wish to hide in a website navigation menu
separated by a space:


 root atts
 tb-black
 UCL Web Services
 section_header_white
 
 
section_subheader_white
 cms-assets/images/ucl0001
 ucl0001
 normal
 yes
 3_columns
 test1 test2


I have a script 'normalmenu' that I will eventually be using to generate a
navigation menu for a website here it is in its present development state:

attobject = context.get_attobject()
navstring = context.get_uclattribute(attobject, 'ucl_navhide')
hiddennavelements = navstring.split(' ')
for hiddennavelement in hiddennavelements:
return hiddennavelement

So the script 'get_attobject' basically looks for an instance of the
attributes object in the current folder, if it doesn't locate one then it
uses acquisition to find one in a parent folder. The script
'get_uclattribute' then gets the nodeValues of the requested node. In this
instance its ucl_navhide, then I split the 'navstring' string at the spaces
and attempt the for-loop to output each of the values. 

Unfortunately it appears I am unable to loop through each of the list items
in hiddennavelements, as it only returns the first value & will not repeat.

Strangely if I test to output the value of hiddennavelements it looks like
this: [u'test1', u'test2'] which I believe the u refers to Unicode, although
I could be wrong. Even more bizarrely if I test the len(hiddennavelements)
it returns the correct result (2), so why wont my for-loop work?

Hope someone can help, or point out my schoolboy error.

Jon 



-- 
http://mail.python.org/mailman/listinfo/python-list