Re: a question about list as an element in a tuple

2014-02-19 Thread Marko Rauhamaa
Marko Rauhamaa :

> operator.add(x, y) [...] leaves x and y intact and must return a new
> object.

Well, if the addition doesn't modify x, the method can of course return
x.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: a question about list as an element in a tuple

2014-02-19 Thread Marko Rauhamaa
John O'Hagan :

> The weirdest part for me is this:
>
 t = ([],)
 l = t[0]
 l is t[0]
> True
 l += [1]
 t[0] += [1]
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'tuple' object does not support item assignment
>
> Whether there is an error or not depends on the name used for the
> object!

Nice catch! The += operator rebinds the reference even if the object
wouldn't change:

   >>> t = 1,
   >>> t[0] = t[0]
   Traceback (most recent call last):
 File "", line 1, in 
   TypeError: 'tuple' object does not support item assignment

See also:

   >>> a = []
   >>> b = a
   >>> a = a + [1]
   >>> a is b
   False
   >>> a = []
   >>> b = a
   >>> a += [1]
   >>> a is b
   True

This behavior is not a bug, though. http://docs.python.org/3.2/library/operator.html#inplace-operators>:

  for example, the statement x += y is equivalent to x =
  operator.iadd(x, y)

operator.iadd(x, y) modifies x in place and returns x. However, (http://docs.python.org/3.2/library/operator.html#operator.add>) x + y is
dealt with by operator.add(x, y), which leaves x and y intact and must
return a new object.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: a question about list as an element in a tuple

2014-02-18 Thread John O'Hagan
On Mon, 16 Dec 2013 11:30:13 +0800
liuerfire Wang  wrote:

> Just like below:
> 
> In [1]: a = ([], [])
> 
> In [2]: a[0].append(1)
> 
> In [3]: a
> Out[3]: ([1], [])
> 
> In [4]: a[0] += [1]
> ---
> TypeError Traceback (most recent call
> last)  in ()
> > 1 a[0] += [1]
> 
> TypeError: 'tuple' object does not support item assignment
> 
> In [5]: a
> Out[5]: ([1, 1], [])
> 
> no problem, there is an exception. But a is still changed.
> 
> is this a bug, or could anyone explain it?
> 
> thanks.
> 

This thread from two years ago deals with this in some detail:

https://mail.python.org/pipermail/python-list/2012-February/619265.html

It's one of those things that is hard to resolve in a way that makes
sense in every situation. The weirdest part for me is this:

>>> t = ([],)
>>> l = t[0]
>>> l is t[0]
True
>>> l += [1]
>>> t[0] += [1]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment

Whether there is an error or not depends on the name used for the
object!

--

John


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


Re: a question about list as an element in a tuple

2013-12-15 Thread rusi
On Monday, December 16, 2013 9:27:11 AM UTC+5:30, Chris Angelico wrote:
> On Mon, Dec 16, 2013 at 2:30 PM, liuerfire Wang  wrote:
> > TypeError: 'tuple' object does not support item assignment
> > In [5]: a
> > Out[5]: ([1, 1], [])
> > no problem, there is an exception. But a is still changed.
> > is this a bug, or could anyone explain it?

> It's not a bug, but it's a bit confusing. Here's what happens. The
> augmented assignment operator += triggers an in-place addition (where
> possible; for lists, it's possible), so the original list will be
> changed:

> >>> a = [1]
> >>> b = a
> >>> a += [2]
> >>> b
> [1, 2]

> Whereas using separate assignment and addition creates a new list:

> >>> a = a + [3]
> >>> a
> [1, 2, 3]
> >>> b
> [1, 2]

> To handle both mutable types (like list) and immutable ones (like
> str), the augmented assignment operators have to be able to choose
> whether or not they change their object:

> >>> a = "1"
> >>> b = a
> >>> a += "2"
> >>> b
> '1'
> >>> a
> '12'

> So what happens under the hood is, more or less:

> a += [2]
> # ... is equivalent to ...
> a = a.__iadd__([2])

> Which can be explored interactively:

> >>> a = [1]
> >>> a.__iadd__([2])
> [1, 2]
> >>> a
> [1, 2]

> The __iadd__ function ("in-place add") returns the new result, and in
> the case of the list, that's done by changing the list. The assignment
> is then done, which does nothing here, but with strings, is the
> critical part of the job. So far, so good.

> Now, when that result gets assigned to the tuple, we have a problem.
> Tuples are immutable - can't change length (no appending), and can't
> assign to elements. So when the final step happens, an exception is
> thrown. At that point, the tuple is complaining "Hey, you can't assign
> to me!", but the list has already done the appending, and it's too
> late to undo that. So the list has changed, and when you go look at
> it, you see the change (since the list is the same whether you find it
> from the tuple or somewhere else), which creates the confusing
> situation of throwing an exception after doing exactly what you
> wanted.

> Python exceptions aren't like SQL errors, causing a rollback of the
> whole transaction. Or, more generally, Python expressions and
> statements aren't transactional. So it's entirely possible, if a
> little confusing, for part of a job to happen. Let's take another
> example that has side effects:

> tup = (1,2,3)
> tup[2] = input("Enter something: ")   # use raw_input() in Python 2

> Tuple assignment can't work... but it's fairly clear that this
> _should_ still show the prompt and wait for the user to type
> something, and only throw the exception later on. It's not as obvious
> in the augmented assignment example, but both are actually doing the
> same thing.

> Hope that helps!

Heh!
Nice question... even nicer explanation!!

I thought I knew that imperative programming is a bad idea:
http://blog.languager.org/2012/11/imperative-programming-lessons-not.html

Never cease to be surprised how bad an idea it is!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: a question about list as an element in a tuple

2013-12-15 Thread Chris Angelico
On Mon, Dec 16, 2013 at 2:30 PM, liuerfire Wang  wrote:
> TypeError: 'tuple' object does not support item assignment
>
> In [5]: a
> Out[5]: ([1, 1], [])
>
> no problem, there is an exception. But a is still changed.
>
> is this a bug, or could anyone explain it?

It's not a bug, but it's a bit confusing. Here's what happens. The
augmented assignment operator += triggers an in-place addition (where
possible; for lists, it's possible), so the original list will be
changed:

>>> a = [1]
>>> b = a
>>> a += [2]
>>> b
[1, 2]

Whereas using separate assignment and addition creates a new list:

>>> a = a + [3]
>>> a
[1, 2, 3]
>>> b
[1, 2]

To handle both mutable types (like list) and immutable ones (like
str), the augmented assignment operators have to be able to choose
whether or not they change their object:

>>> a = "1"
>>> b = a
>>> a += "2"
>>> b
'1'
>>> a
'12'

So what happens under the hood is, more or less:

a += [2]
# ... is equivalent to ...
a = a.__iadd__([2])

Which can be explored interactively:

>>> a = [1]
>>> a.__iadd__([2])
[1, 2]
>>> a
[1, 2]

The __iadd__ function ("in-place add") returns the new result, and in
the case of the list, that's done by changing the list. The assignment
is then done, which does nothing here, but with strings, is the
critical part of the job. So far, so good.

Now, when that result gets assigned to the tuple, we have a problem.
Tuples are immutable - can't change length (no appending), and can't
assign to elements. So when the final step happens, an exception is
thrown. At that point, the tuple is complaining "Hey, you can't assign
to me!", but the list has already done the appending, and it's too
late to undo that. So the list has changed, and when you go look at
it, you see the change (since the list is the same whether you find it
from the tuple or somewhere else), which creates the confusing
situation of throwing an exception after doing exactly what you
wanted.

Python exceptions aren't like SQL errors, causing a rollback of the
whole transaction. Or, more generally, Python expressions and
statements aren't transactional. So it's entirely possible, if a
little confusing, for part of a job to happen. Let's take another
example that has side effects:

tup = (1,2,3)
tup[2] = input("Enter something: ")   # use raw_input() in Python 2

Tuple assignment can't work... but it's fairly clear that this
_should_ still show the prompt and wait for the user to type
something, and only throw the exception later on. It's not as obvious
in the augmented assignment example, but both are actually doing the
same thing.

Hope that helps!

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


a question about list as an element in a tuple

2013-12-15 Thread liuerfire Wang
Just like below:

In [1]: a = ([], [])

In [2]: a[0].append(1)

In [3]: a
Out[3]: ([1], [])

In [4]: a[0] += [1]
---
TypeError Traceback (most recent call last)
 in ()
> 1 a[0] += [1]

TypeError: 'tuple' object does not support item assignment

In [5]: a
Out[5]: ([1, 1], [])

no problem, there is an exception. But a is still changed.

is this a bug, or could anyone explain it?

thanks.


-- 
Best regards.
/**
google+: +liuerfire  twitter:
@liuerfire
蛋疼不蛋疼的都可以试着点一下~^_^~ 
***/
-- 
https://mail.python.org/mailman/listinfo/python-list


About list Pyclutter

2011-04-02 Thread craf
Hi.

Does anyone know if pyclutter has a mailing list?

Regards.

Cristian Abarzúa

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


Re: Dumb Stupid Question About List and String

2010-09-01 Thread Xavier Ho
2010/9/2 Alban Nona 

> Hello Xavier, working great ! thank you very much ! :p
> Do you know by any chance if dictionnary can be sorted asthis:
>

Look at the sorted() global function in the Python API. ;]

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


Re: Dumb Stupid Question About List and String

2010-09-01 Thread MRAB

On 01/09/2010 17:49, Alban Nona wrote:

Hello Xavier,

Thank you :)

Well what Iam trying to generate is that kind of result:

listn1=['ELM001_DIF', 'ELM001_SPC', 'ELM001_RFL', 'ELM001_SSS',
'ELM001_REFR', 'ELM001_ALB', 'ELM001_AMB', 'ELM001_NRM', 'ELM001_MVE',
'ELM001_DPF', 'ELM001_SDW', 'ELM001_MAT', 'ELM001_WPP']

listn2 = ['ELM002_DIF', 'ELM002_SPC', 'ELM002_RFL', 'ELM002_SSS',
'ELM002_REFR', 'ELM002_ALB', 'ELM002_AMB', 'ELM002_NRM', 'ELM002_MVE',
'ELM002_DPF', 'ELM002_SDW', 'ELM002_MAT', 'ELM002_WPP']

etc...

The thing is, the first list will be generated automatically. (so there
will be unknow versions of ELM00x)
that why Im trying to figure out how to genere variable and list in an
automatic way.

Can you tell me if its not clear please ? :P
my english still need improvement when Im trying to explain scripting
things.


[snip]
Create a dict in which the key is the "ELEM" part and the value is a
list of those entries which begin with that "ELEM" part.

For example, if the entry is 'ELEM001_DIF' then the key is 'ELEM001',
which is the first 7 characters of entry, or entry[ : 7].

Something like this:

elem_dict = {}
for entry in list_of_entries:
key = entry[ : 7]
if key in elem_dict:
elem_dict[key].append(entry)
else:
elem_dict[key] = [entry]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-09-01 Thread Xavier Ho
On 2 September 2010 02:49, Alban Nona  wrote:

> Well what Iam trying to generate is that kind of result:
>
> listn1=['ELM001_DIF', 'ELM001_SPC', 'ELM001_RFL', 'ELM001_SSS',
> 'ELM001_REFR', 'ELM001_ALB', 'ELM001_AMB', 'ELM001_NRM', 'ELM001_MVE',
> 'ELM001_DPF', 'ELM001_SDW', 'ELM001_MAT', 'ELM001_WPP']
>
> listn2 = ['ELM002_DIF', 'ELM002_SPC', 'ELM002_RFL', 'ELM002_SSS',
> 'ELM002_REFR', 'ELM002_ALB', 'ELM002_AMB', 'ELM002_NRM', 'ELM002_MVE',
> 'ELM002_DPF', 'ELM002_SDW', 'ELM002_MAT', 'ELM002_WPP']
>
> etc...
>

Have a look at http://www.ideone.com/zlBeB .
I took some liberty and renamed some of your variables. I wanted to show you
what I (personally) think as good practices in python, from naming
conventions to how to use the list and dictionary, and so on. Also, 4-spaces
indent. I noticed you have 5 for some reason, but that's none of my business
now. I hope my comments explain what they do, and why they are that way.


> The thing is, the first list will be generated automatically. (so there
> will be unknow versions of ELM00x)
> that why Im trying to figure out how to genere variable and list in an
> automatic way.
>

Yes, that's totally possible. See range() (and xrange(), possibly) in the
Python API.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-09-01 Thread Alban Nona
Hello Xavier,

Thank you :)

Well what Iam trying to generate is that kind of result:

listn1=['ELM001_DIF', 'ELM001_SPC', 'ELM001_RFL', 'ELM001_SSS',
'ELM001_REFR', 'ELM001_ALB', 'ELM001_AMB', 'ELM001_NRM', 'ELM001_MVE',
'ELM001_DPF', 'ELM001_SDW', 'ELM001_MAT', 'ELM001_WPP']

listn2 = ['ELM002_DIF', 'ELM002_SPC', 'ELM002_RFL', 'ELM002_SSS',
'ELM002_REFR', 'ELM002_ALB', 'ELM002_AMB', 'ELM002_NRM', 'ELM002_MVE',
'ELM002_DPF', 'ELM002_SDW', 'ELM002_MAT', 'ELM002_WPP']

etc...

The thing is, the first list will be generated automatically. (so there will
be unknow versions of ELM00x)
that why Im trying to figure out how to genere variable and list in an
automatic way.

Can you tell me if its not clear please ? :P
my english still need improvement when Im trying to explain scripting
things.

2010/9/1 Xavier Ho 

> On 2 September 2010 01:11, Alban Nona  wrote:
>
>> Hello,
>>
>> seems to have the same error with python.
>> In fact I was coding within nuke, a 2d compositing software (not the best)
>> unfortunately, I dont see how I can use dictionnary to do what I would
>> like to do.
>>
>
> Hello Alban,
>
> The reason it's printing only the ELM004 elements is because the variable,
> first, is 'ELM004' when your code goes to line 29.
>
> I noticed you're using variables created from the for loop out of its block
> as well. Personally I wouldn't recommend it as good practice. There are ways
> around it.
>
> Could you explain briefly what you want to achieve with this program?
> What's the desired sample output?
>
> Cheers,
> Xav
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-09-01 Thread Xavier Ho
On 2 September 2010 01:11, Alban Nona  wrote:

> Hello,
>
> seems to have the same error with python.
> In fact I was coding within nuke, a 2d compositing software (not the best)
> unfortunately, I dont see how I can use dictionnary to do what I would like
> to do.
>

Hello Alban,

The reason it's printing only the ELM004 elements is because the variable,
first, is 'ELM004' when your code goes to line 29.

I noticed you're using variables created from the for loop out of its block
as well. Personally I wouldn't recommend it as good practice. There are ways
around it.

Could you explain briefly what you want to achieve with this program? What's
the desired sample output?

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


Re: Dumb Stupid Question About List and String

2010-09-01 Thread Alban Nona
Hello,

seems to have the same error with python.
In fact I was coding within nuke, a 2d compositing software (not the best)
unfortunately, I dont see how I can use dictionnary to do what I would like
to do.

2010/9/1 Xavier Ho 

> On 2 September 2010 00:47, Alban Nona  wrote:
>
>> Hello,
>>
>> So I figure out this night how to create automatically varibales via
>> vars(), the script seems to work, exept that where it should give me a list
>> like :
>> [ELM004_DIF,ELM004_SPC,ELM004_RFL,ELM004_SSS, ELM004_REFR, ELM004_ALB,
>> etc...] it gave me just one entry in my list, and the last one [ELM004_WPP]
>> Any Ideas why that please ?
>>
>> http://pastebin.com/7CDbVgdD
>
>
> Some comments:
>
> 1) Avoid overwriting global functions like list as a variable name. If you
> do that, you won't be able to use list() later in your code, and nor can
> anyone else who imports your code.
> 2) I'm a bit iffy about automatic variable generations. Why not just use a
> dictionary? What do others on comp.lang.python think?
> 3) I'm getting an error from your code, and it doesn't match with what you
> seem to get:
>
> # output
>
> ELM004_DIF
> ELM004_SPC
> ELM004_RFL
> ELM004_SSS
> ELM004_REFR
> ELM004_ALB
> ELM004_AMB
> ELM004_NRM
> ELM004_MVE
> ELM004_DPF
> ELM004_SDW
> ELM004_MAT
> ELM004_WPP
> Traceback (most recent call last):
>   File "Test.py", line 33, in 
> print ELM001
> NameError: name 'ELM001' is not defined
>
> Did you get any compiler errors? I'm using Python 2.7
>
> Cheers,
> Xav
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-09-01 Thread Xavier Ho
On 2 September 2010 00:47, Alban Nona  wrote:

> Hello,
>
> So I figure out this night how to create automatically varibales via
> vars(), the script seems to work, exept that where it should give me a list
> like :
> [ELM004_DIF,ELM004_SPC,ELM004_RFL,ELM004_SSS, ELM004_REFR, ELM004_ALB,
> etc...] it gave me just one entry in my list, and the last one [ELM004_WPP]
> Any Ideas why that please ?
>
> http://pastebin.com/7CDbVgdD


Some comments:

1) Avoid overwriting global functions like list as a variable name. If you
do that, you won't be able to use list() later in your code, and nor can
anyone else who imports your code.
2) I'm a bit iffy about automatic variable generations. Why not just use a
dictionary? What do others on comp.lang.python think?
3) I'm getting an error from your code, and it doesn't match with what you
seem to get:

# output
ELM004_DIF
ELM004_SPC
ELM004_RFL
ELM004_SSS
ELM004_REFR
ELM004_ALB
ELM004_AMB
ELM004_NRM
ELM004_MVE
ELM004_DPF
ELM004_SDW
ELM004_MAT
ELM004_WPP
Traceback (most recent call last):
  File "Test.py", line 33, in 
print ELM001
NameError: name 'ELM001' is not defined

Did you get any compiler errors? I'm using Python 2.7

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


Re: Dumb Stupid Question About List and String

2010-09-01 Thread Alban Nona
Hello,

So I figure out this night how to create automatically varibales via vars(),
the script seems to work, exept that where it should give me a list like :
[ELM004_DIF,ELM004_SPC,ELM004_RFL,ELM004_SSS, ELM004_REFR, ELM004_ALB,
etc...] it gave me just one entry in my list, and the last one [ELM004_WPP]
Any Ideas why that please ?

http://pastebin.com/7CDbVgdD








2010/9/1 Xavier Ho 

> On 1 September 2010 12:00, Alban Nona  wrote:
>
>> @Xavier: ShaDoW, WorldPositionPoint (which is the same thing as
>> WordPointCloud passe) :)
>>
>
> Aha! That's what I was missing.
>
> Cheers,
> Xav
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-08-31 Thread Xavier Ho
On 1 September 2010 12:00, Alban Nona  wrote:

> @Xavier: ShaDoW, WorldPositionPoint (which is the same thing as
> WordPointCloud passe) :)
>

Aha! That's what I was missing.

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


Fwd: Dumb Stupid Question About List and String

2010-08-31 Thread Alban Nona
In fact, the First list (wich contain "Elm001, Elm002, Elm003) will be
generated automatically from files that I have in a directory, that's why I
cant write the same code for Elm002, 003, etc... Because Ill not know how
many Elm there will be.


2010/8/31 MRAB 

> On 01/09/2010 03:00, Alban Nona wrote:
>
>  @MRAB, thank you, but what if there are like 40 entries like 'Elem00x' ?
>> is there a way to do it automaticaly ?
>>
>>  If you can do it for 'Elem001', I'm sure you could write some code to
> produce a list of 'Elem001', 'Elem002', etc, and check whether any are
> substrings, just as was done for 'Elem001'.
>
>
>  @Xavier: ShaDoW, WorldPositionPoint (which is the same thing as
>> WordPointCloud passe) :)
>>
>> Anyway, thank you !
>>
>>  [snip]
> Do you want separate lists for 'Elem001', 'Elem002', etc, or all in the
> same list?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-08-31 Thread MRAB

On 01/09/2010 03:00, Alban Nona wrote:

@MRAB, thank you, but what if there are like 40 entries like 'Elem00x' ?
is there a way to do it automaticaly ?


If you can do it for 'Elem001', I'm sure you could write some code to
produce a list of 'Elem001', 'Elem002', etc, and check whether any are
substrings, just as was done for 'Elem001'.


@Xavier: ShaDoW, WorldPositionPoint (which is the same thing as
WordPointCloud passe) :)

Anyway, thank you !


[snip]
Do you want separate lists for 'Elem001', 'Elem002', etc, or all in the
same list?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-08-31 Thread Alban Nona
@MRAB, thank you, but what if there are like 40 entries like 'Elem00x' ? is
there a way to do it automaticaly ?

@Xavier: ShaDoW, WorldPositionPoint (which is the same thing as
WordPointCloud passe) :)

Anyway, thank you !

2010/8/31 Xavier Ho 

> On 1 September 2010 07:57, Alban Nona  wrote:
>
>> listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM", "MVE",
>> "DPF", "SDW", "MAT", "WPP"]
>>
>
> Out of curiosity, could you briefly mention what "SDW" and "WPP" passes
> are? I've worked out the rest, and these two are riddling my brain.
>
> (On topic: If you want only the elements starting with ELM001, or whatever,
> use a if condition like what MRAB posted.)
>
> Cheers,
> Xav
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-08-31 Thread Xavier Ho
On 1 September 2010 07:57, Alban Nona  wrote:

> listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM", "MVE",
> "DPF", "SDW", "MAT", "WPP"]
>

Out of curiosity, could you briefly mention what "SDW" and "WPP" passes are?
I've worked out the rest, and these two are riddling my brain.

(On topic: If you want only the elements starting with ELM001, or whatever,
use a if condition like what MRAB posted.)

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


Re: Dumb Stupid Question About List and String

2010-08-31 Thread MRAB

On 31/08/2010 22:57, Alban Nona wrote:

Just Another Question on this one, Im trying to create that kind of
thing in code now:

#GENERE ET INCREMENT LE NOM DES ELEMENTS

val = 0

list = ["0", "1", "2", "3"]

listEl = []

for n in list:

  val = val + 1

  next = "00" +str(val)

  elem = "ELM"+next

  listEl.append(elem)



#INCREMENT LE NOM DES ELEMENTS AVEC LE NOM DES PASSES

listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM",
"MVE", "DPF", "SDW", "MAT", "WPP"]

listElem = []

for first in listEl:

  for second in listPass:

  listElem.append(first+"_"+second)


print listElem

print listEl


What I would like to do is:

if 'ELM001' Contained in one of the entries of listElem, create a new
list with only 'ELM001' Elements (eg: newList=['ELM001_DIF',
'ELM001_SPC', 'ELM001_RFL', 'ELM001_SSS', 'ELM001_REFR', 'ELM001_ALB',
'ELM001_AMB', 'ELM001_NRM', 'ELM001_MVE', 'ELM001_DPF', 'ELM001_SDW',
'ELM001_MAT', 'ELM001_WPP']

Damn Im so lost with this tables and loop, Im always trying to
understand in which way I should do it :/
Any Ideas please ?


How about:

newList = []
for elem in listElem:
if 'ELM001' in elem:
newList.append(elem)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-08-31 Thread Alban Nona
Just Another Question on this one, Im trying to create that kind of thing in
code now:

#GENERE ET INCREMENT LE NOM DES ELEMENTS

val = 0

list = ["0", "1", "2", "3"]

listEl = []

for n in list:

 val = val + 1

 next = "00" +str(val)

 elem = "ELM"+next

 listEl.append(elem)



#INCREMENT LE NOM DES ELEMENTS AVEC LE NOM DES PASSES

listPass = ["DIF","SPC", "RFL", "SSS", "REFR", "ALB", "AMB", "NRM", "MVE",
"DPF", "SDW", "MAT", "WPP"]

listElem = []

for first in listEl:

 for second in listPass:

 listElem.append(first+"_"+second)


print listElem

print listEl

What I would like to do is:

if 'ELM001' Contained in one of the entries of listElem, create a new list
with only 'ELM001' Elements (eg: newList=['ELM001_DIF', 'ELM001_SPC',
'ELM001_RFL', 'ELM001_SSS', 'ELM001_REFR', 'ELM001_ALB', 'ELM001_AMB',
'ELM001_NRM', 'ELM001_MVE', 'ELM001_DPF', 'ELM001_SDW', 'ELM001_MAT',
'ELM001_WPP']

Damn Im so lost with this tables and loop, Im always trying to
understand in which way I should do it :/
Any Ideas please ?


2010/8/31 Alban Nona 

> Well, I have a lot to learn :)
>
> Thank you very much both of you ! it seems to work now :p
>
> 2010/8/31 MRAB 
>
>> On 31/08/2010 20:20, Alban Nona wrote:
>>
>>  Ok, here a solution:
>>>
>>> myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"]
>>>
>>> mySecondList =
>>>
>>> ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]
>>>
>>> for n in myFirstList:
>>>  var = str(n)
>>>
>>
>> Why str(n)?
>>
>> Also, it would be clearer if you used different variables for the
>> different loops.
>>
>>
>>   for n in mySecondList:
>>>  if var in n:
>>>   mySecondList.remove(n)
>>>
>>
>> You shouldn't change the length of a list over which you're iterating.
>> Python will step along the list one entry at a time and won't notice when
>> you remove an entry, so the next one will be skipped. For example:
>>
>> >>> letters = ["a", "b", "c", "d", "e"]
>> >>> for i in letters:
>> ... if i == "b" or i == "c":
>> ... letters.remove(i)
>> ...
>> >>> print letters
>> ['a', 'c', 'd', 'e']
>>
>> It removed "b" and then moved on to the next entry, which is "d"
>> because "b" has been removed and all the following entries have moved
>> down one place. It never sees "c".
>>
>>
>>> print mySecondList
>>>
>>>  [snip]
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-08-31 Thread Alban Nona
Well, I have a lot to learn :)

Thank you very much both of you ! it seems to work now :p

2010/8/31 MRAB 

> On 31/08/2010 20:20, Alban Nona wrote:
>
>> Ok, here a solution:
>>
>> myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"]
>>
>> mySecondList =
>>
>> ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]
>>
>> for n in myFirstList:
>>  var = str(n)
>>
>
> Why str(n)?
>
> Also, it would be clearer if you used different variables for the
> different loops.
>
>
>   for n in mySecondList:
>>  if var in n:
>>   mySecondList.remove(n)
>>
>
> You shouldn't change the length of a list over which you're iterating.
> Python will step along the list one entry at a time and won't notice when
> you remove an entry, so the next one will be skipped. For example:
>
> >>> letters = ["a", "b", "c", "d", "e"]
> >>> for i in letters:
> ... if i == "b" or i == "c":
> ... letters.remove(i)
> ...
> >>> print letters
> ['a', 'c', 'd', 'e']
>
> It removed "b" and then moved on to the next entry, which is "d"
> because "b" has been removed and all the following entries have moved
> down one place. It never sees "c".
>
>
>> print mySecondList
>>
>>  [snip]
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-08-31 Thread Shashwat Anand
On Wed, Sep 1, 2010 at 12:27 AM, Alban Nona  wrote:

> Hi all,
>
> Im stuck on this problem:
> I have a function which return me a list of string (basically the result
> looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"]
> In other hand, I have another list full of that kind of entries:
>
> ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]
>
> I would like to do something like this:
>
> myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"]
> mySecondList =
> ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]
>
> for n in myFirstList:
> if n in mySecondList:
> mySecondList.remove(n)
>
> In fact, what I want to do it to remove entries with the secondlist which
> content the entries of the first one. But it seems to not work like this.
> Someone can help me please ? did I miss something ?
>

You can try this if you don't care about the order.

>>> myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"]
>>> mySecondList =
["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]
>>> list(set(mySecondList).difference(myFirstList))
['FN067_098_MEN_Jin_MVE_v001.0001.exr',
'FN067_098_MEN_Hair_PUZ_v001.0001.exr', 'FR043_010_GEN_NRM_v001.0001.exr',
'FN067_098_JIN_Hair_SPC_v001.0001.exr']

Another example to make this clear.
>>> a = range(10)
>>> b = range(5,15)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> list(set(b).difference(a))
[10, 11, 12, 13, 14]


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


Re: Dumb Stupid Question About List and String

2010-08-31 Thread MRAB

On 31/08/2010 20:20, Alban Nona wrote:

Ok, here a solution:

myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"]

mySecondList =
["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]

for n in myFirstList:
  var = str(n)


Why str(n)?

Also, it would be clearer if you used different variables for the
different loops.


  for n in mySecondList:
  if var in n:
   mySecondList.remove(n)


You shouldn't change the length of a list over which you're iterating. 
Python will step along the list one entry at a time and won't notice 
when you remove an entry, so the next one will be skipped. For example:


>>> letters = ["a", "b", "c", "d", "e"]
>>> for i in letters:
... if i == "b" or i == "c":
... letters.remove(i)
...
>>> print letters
['a', 'c', 'd', 'e']

It removed "b" and then moved on to the next entry, which is "d"
because "b" has been removed and all the following entries have moved
down one place. It never sees "c".



print mySecondList


[snip]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-08-31 Thread Chris Rebert
On Tue, Aug 31, 2010 at 12:20 PM, Alban Nona  wrote:
> Ok, here a solution:

> for n in myFirstList:
>  var = str(n)

n is already a string, so the previous line doesn't do anything useful.

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


Re: Dumb Stupid Question About List and String

2010-08-31 Thread MRAB

On 31/08/2010 19:57, Alban Nona wrote:

Hi all,

Im stuck on this problem:
I have a function which return me a list of string (basically the result
looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"]
In other hand, I have another list full of that kind of entries:
["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]

I would like to do something like this:

myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"]
mySecondList =
["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]

for n in myFirstList:
 if n in mySecondList:
 mySecondList.remove(n)

In fact, what I want to do it to remove entries with the secondlist
which content the entries of the first one. But it seems to not work
like this.
Someone can help me please ? did I miss something ?


Your code is asking whether, for example, "FN067_098_MEN" is in
mySecondList. It isn't. mySecondList contains
"FN067_098_MEN_Hair_PUZ_v001.0001.exr", but that's not the same as
"FN067_098_MEN".

If I understand you correctly, you want to remove entries from
mySecondList which have an entry of myFirstList as a substring.

Here's one solution:

result_list = []
for second in mySecondList:
if not any(first in second for first in myFirstList):
result_list.append(second)

mySecondList = result_list
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dumb Stupid Question About List and String

2010-08-31 Thread Alban Nona
Ok, here a solution:

myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"]

mySecondList =
["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]

for n in myFirstList:

 var = str(n)

 for n in mySecondList:

 if var in n:

  mySecondList.remove(n)

print mySecondList


:)


2010/8/31 Alban Nona 

> Hi all,
>
> Im stuck on this problem:
> I have a function which return me a list of string (basically the result
> looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"]
> In other hand, I have another list full of that kind of entries:
>
> ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]
>
> I would like to do something like this:
>
> myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"]
> mySecondList =
> ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]
>
> for n in myFirstList:
> if n in mySecondList:
> mySecondList.remove(n)
>
> In fact, what I want to do it to remove entries with the secondlist which
> content the entries of the first one. But it seems to not work like this.
> Someone can help me please ? did I miss something ?
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Dumb Stupid Question About List and String

2010-08-31 Thread Alban Nona
Hi all,

Im stuck on this problem:
I have a function which return me a list of string (basically the result
looks like: ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"]
In other hand, I have another list full of that kind of entries:
["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]

I would like to do something like this:

myFirstList = ["FN067_098_MEN", FN067_098_JIN", FN067_098_BG"]
mySecondList =
["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]

for n in myFirstList:
if n in mySecondList:
mySecondList.remove(n)

In fact, what I want to do it to remove entries with the secondlist which
content the entries of the first one. But it seems to not work like this.
Someone can help me please ? did I miss something ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about list extension

2010-04-16 Thread J
On Fri, Apr 16, 2010 at 15:16, Terry Reedy  wrote:
> On 4/16/2010 9:41 AM, J wrote:
>>
>> Ok... I know pretty much how .extend works on a list... basically it
>> just tacks the second list to the first list... like so:
>>
> lista=[1]
> listb=[2,3]
> lista.extend(listb)
> print lista;
>>
>> [1, 2, 3]
>
> This shows right here that lista is extended in place. If you are not
> convinced, print(id(lista)) before and after.

Thanks for the explanations, everyone...

I was just a bit confused about how .extend was working... I
originally thought that it returned a new object and linked lista to
that, but I realize that it directly manipulates the list object
instead...

I'm not sure why I got that idea stuck in my head, but it was there,
so I asked :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about list extension

2010-04-16 Thread Terry Reedy

On 4/16/2010 9:41 AM, J wrote:

Ok... I know pretty much how .extend works on a list... basically it
just tacks the second list to the first list... like so:


lista=[1]
listb=[2,3]
lista.extend(listb)
print lista;

[1, 2, 3]


This shows right here that lista is extended in place. If you are not 
convinced, print(id(lista)) before and after.



what I'm confused on is why this returns None:


lista=[1]
listb=[2,3]
print lista.extend(listb)

None


It is conventional in Python (at least the stdlib) that methods that 
mutate mutable objects 'in-place' return None to clearly differentiate 
them from methods that return new objects. There are pluses and minuses 
but such it is.


Terry Jan Reedy

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


Re: question about list extension

2010-04-16 Thread J. Cliff Dyer
On Sat, 2010-04-17 at 00:37 +1000, Lie Ryan wrote:
> On 04/16/10 23:41, J wrote:

> > So, what I'm curious about, is there a list comprehension or other
> > means to reduce that to a single line?
> 
> from itertools import chain
> def printout(*info):
> print '\n'.join(map(str, chain(*info)))
> 
> or using generator comprehension
> 
> from itertools import chain
> def printout(*info):
> print '\n'.join(str(x) for x in chain(*info))


It's even easier if you don't need to modify lista.  

print lista + listb


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


Re: question about list extension

2010-04-16 Thread Lie Ryan
On 04/16/10 23:41, J wrote:
> Ok... I know pretty much how .extend works on a list... basically it
> just tacks the second list to the first list... like so:
> 
 lista=[1]
 listb=[2,3]
 lista.extend(listb)
 print lista;
> [1, 2, 3]
> 
> what I'm confused on is why this returns None:
> 
 lista=[1]
 listb=[2,3]
 print lista.extend(listb)
> None
 print lista
> [1, 2, 3]
> 
> So why the None? Is this because what's really happening is that
> extend() and append() are directly manipulating the lista object and
> thus not actuall returning a new object?

In python every function that does not explicitly returns a value or use
a bare return returns None. So:

def foo():
pass
def bar():
return

print foo()
print bar()

you can say that returning None is python's equivalent to void return
type in other languages.

> Even if that assumption of mine is correct, I would have expected
> something like this to work:
> 
 lista=[1]
 listb=[2,3]
 print (lista.extend(listb))
> None

Why would these has to be different?
print None
print (None)



> So, what I'm curious about, is there a list comprehension or other
> means to reduce that to a single line?

from itertools import chain
def printout(*info):
print '\n'.join(map(str, chain(*info)))

or using generator comprehension

from itertools import chain
def printout(*info):
print '\n'.join(str(x) for x in chain(*info))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about list extension

2010-04-16 Thread Bruno Desthuilliers

J a écrit :

Ok... I know pretty much how .extend works on a list... basically it
just tacks the second list to the first list... like so:


lista=[1]
listb=[2,3]
lista.extend(listb)
print lista;

[1, 2, 3]

what I'm confused on is why this returns None:



So why the None? Is this because what's really happening is that
extend() and append() are directly manipulating the lista object and
thus not actuall returning a new object?


Exactly.


Even if that assumption of mine is correct, I would have expected
something like this to work:


lista=[1]
listb=[2,3]
print (lista.extend(listb))

None


So what ? It JustWork(tm). list.extend returns None, so "None" is 
printed !-)



(snip)


So changing debugger.printout() to:

   def printout(self,*info):

lets me pass in multiple lists... and I can do this:

   for tlist in info:
   for item in tlist:
print item

which works well...

So, what I'm curious about, is there a list comprehension or other
means to reduce that to a single line?


Why do you think the above code needs to be "reduced to a single line" ? 
 What's wrong with this snippet ???




It's more of a curiosity thing at this point...  and not a huge
difference in code... I was just curious about how to make that work.


Uh, ok.

What about:

from itertools import chain

def printout(*infos):
   print "\n".join("%s" % item for item in chain(*infos))


HTH


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


question about list extension

2010-04-16 Thread J
Ok... I know pretty much how .extend works on a list... basically it
just tacks the second list to the first list... like so:

>>> lista=[1]
>>> listb=[2,3]
>>> lista.extend(listb)
>>> print lista;
[1, 2, 3]

what I'm confused on is why this returns None:

>>> lista=[1]
>>> listb=[2,3]
>>> print lista.extend(listb)
None
>>> print lista
[1, 2, 3]

So why the None? Is this because what's really happening is that
extend() and append() are directly manipulating the lista object and
thus not actuall returning a new object?

Even if that assumption of mine is correct, I would have expected
something like this to work:

>>> lista=[1]
>>> listb=[2,3]
>>> print (lista.extend(listb))
None

The reason this is bugging me right now is that I'm working on some
code.  My program has a debugger class that takes a list as it's only
(for now) argument.  That list, is comprised of messages I want to
spit out during debug, and full output from system commands being run
with Popen...

So the class looks something like this:

class debugger():
def printout(self,info):
for line in info:
print "DEBUG: %s" % line


and later on, it get's called like this

meminfo = Popen('cat
/proc/meminfo',shell=True,stdout=PIPE).communicate[0].splitlines()

if debug:
debugger.printout(meminfo)

easy enough

BUT, what if I have several lists I want to pass on multiple lists...

So changing debugger.printout() to:

   def printout(self,*info):

lets me pass in multiple lists... and I can do this:

   for tlist in info:
   for item in tlist:
print item

which works well...

So, what I'm curious about, is there a list comprehension or other
means to reduce that to a single line?

I tried this, which didn't work because I'm messing up the syntax, somehow:

def func(*info)
print [ i for tlist in info for i in tlist ]

so can someone help me understand a list comprehension that will turn
those three lines into on?

It's more of a curiosity thing at this point...  and not a huge
difference in code... I was just curious about how to make that work.

Cheers,

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


Re: Question about list comprehension/standard "for" disparities

2010-03-31 Thread Steve Holden
Nathan Rice wrote:
> I was just wondering, why the list/generator and standard "for" have
> disparities?
> 
> It would be really nice to be able to do:
> 
> for x in y if foo:
> ...
> 
> rather than:
> 
> for x in (x for x in y if foo):
> ...
> 
But it's not much of an issue when you can easily write

for x in y:
if foo:
...

is it? What's the advantage of your preferred format that overrides its
reduced readability?

> Also, from a style standpoint, I prefer to extract the loop logic into a
> function if it's more than a few lines long.  As a result, most of my
> loops are of the form:
> 
> for x in y:
> bar(x)
> 
> So I frequently end up using map.  As I understand it, there is some
> discussion of removing map() in favor of comprehensions.  Is there any
> reason why the for syntax could not be expanded to accommodate
> statements of the form:
> 
> bar(x) for x in y
> 
> ?
> 
Put parentheses around it and you have a generator expression, which
sounds like it's exactly what you want: a lazy way of producing a
sequence of values:

>>> y = ["this", "that", "and", "the", "other"]
>>> def bar(x):
... return 2*x
...
>>> ge = (bar(x) for x in y)
>>> ge

>>> for x in ge:
...   print x
...
thisthis
thatthat
andand
thethe
otherother
>>>

If you need to use the sequence repeatedly then a list comprehension is
clearly better, since you don't exhaust it by iterating over it.

I doubt map's going to disappear, but neither are comprehensions or
generator expressions.

> This inconsistency really bothered me when I started playing with
> python, and it seems kind of at-odds with the "one right way to do
> things" mentality.
> 
That's the Platonic ideal, but the real world is a dirty place and
Python lives firmly in the real world!

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Question about list comprehension/standard "for" disparities

2010-03-31 Thread Nathan Rice
I was just wondering, why the list/generator and standard "for" have
disparities?

It would be really nice to be able to do:

for x in y if foo:
...

rather than:

for x in (x for x in y if foo):
...

Also, from a style standpoint, I prefer to extract the loop logic into a
function if it's more than a few lines long.  As a result, most of my loops
are of the form:

for x in y:
bar(x)

So I frequently end up using map.  As I understand it, there is some
discussion of removing map() in favor of comprehensions.  Is there any
reason why the for syntax could not be expanded to accommodate statements of
the form:

bar(x) for x in y

?

This inconsistency really bothered me when I started playing with python,
and it seems kind of at-odds with the "one right way to do things"
mentality.

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


Re: Questions about list-creation

2009-12-01 Thread Manuel Graune

Thanks to all of you. You have been most helpful.

Regards,

Manuel Graune

-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about list-creation

2009-11-30 Thread Terry Reedy

Manuel Graune wrote:

in (most) python documentation the syntax "list()"
and "[]" is treated as being more or less the same
thing.


Untrue. List() and [] happen to both evaluate to the same thing, an 
empty list. But there is no reason to expect list() and 
[] to always evaluate to the same thing. The docs for list() 
calls and [] displays and comprehensions are quite different.


In particular, they clearly say that [x] interprets x as an item and 
creates a list with one item, x, while list(x) interprets x as an 
iterable, and creates a list with multiple items, the items of x. So. in 
particular, list([]) != [[]].



For example "help([])" and "help(list())" point
to the same documentation.


This has nothing to do with list(text) and [text]. [] evaluates to an 
instance that has no doc string, so help backs up to its class. Compare


>>> help(1)
Help on int object:
...

The alternative to to print nothing, which would not be very helpful.

Try

>>> help()
...
help> topics

and you will see that there is a topic LISTLITERALS, though not one for 
comprehensions or sets or even generators. The list of topics seems not 
to have been kept up to date.


Terry Jan Reedy

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


Re: Questions about list-creation

2009-11-30 Thread Luis Zarrabeitia
On Monday 30 November 2009 12:22:17 pm Manuel Graune wrote:
>
> when using local variables in list comprehensions, say
>
> a=[i for i in xrange(10)]
>
> the local variable is not destroyed afterwards:
[...]
> b=list(j for j in xrange(10))
>
> the local variable is destroyed after use:

Actually, [] and list() are not the same. For instance, list(1,2) rises an 
error, while [1,2] is the list with two elements.

The comprehension is just a syntactic contruct that allows you to simplify the 
creation of lists, while the list() "function" (it is a class, actually) 
receives an iterable object and returns a list.

What you seem to be confused about is the construct:

(j for j in xrange(10))

That is called a generator expression, and it is very similar to the list 
comprehension, except that it builds an iterator (instead of a list, i.e, the 
xrange(10) is not consumed until it is needed), and the loop variable 
doesn't "leak" outside.

When you do b=list(j for j in xrange(10)), you are actually doing

b=list((j for j in xrange(10)))

(note the extra set of parenthesis - python lets you ommit those), i.e, you 
are calling the list() "function" with a single argument, an iterable that 
contains all the elements of xrange(10). You could be calling

foobar(j for j in xrange(10))

instead.

And I think I lost my way... I'm sleepy. If I confused you, sorry... and if 
I'm helped you, thank you for letting me :D.

Cya.

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about list-creation

2009-11-30 Thread Stephen Hansen
On Mon, Nov 30, 2009 at 9:22 AM, Manuel Graune wrote:

> in (most) python documentation the syntax "list()"
> and "[]" is treated as being more or less the same
> thing. For example "help([])" and "help(list())" point
> to the same documentation. Since there are at least
> two cases where this similarity is not the case, (see below)
> can someone explain the reasoning behind this and point to
> further / relevant documentation?
> (To clarify: I am not complaining about this, just asking.)
>

They -do- pretty much the same thing, but you can't quite treat them as two
forms which can be exchanged at a whim.

[] is the syntax for creating a list literal in source code. Its also the
syntax for list comprehensions. A list comprehension is an expression that
constructs a list all at once.

list() is a function (type/constructor/...) which accepts any iterable as an
argument (or None), and uses it to construct a list, returning it.

Those two things are very different, although in the end they both produce
lists: one is syntax, the other is a function which has to be called.

1.)
>
> when using local variables in list comprehensions, say
>
> a=[i for i in xrange(10)]
>
> the local variable is not destroyed afterwards:
>
> print "a",a
> print "i",i
>
> using the similar code
>

List comprehensions "leaked", as more of an implementation detail I believe
then anything else: in Python 3 it was removed, to better match generator
expressions (IIRC).


>
> b=list(j for j in xrange(10))
>
> the local variable is destroyed after use:
>
> print "b",b
> print "j",j
>
>
But see, this is something completely different.

(j for j in xrange(10))

is NOT a list comprehension. Its a generator comprehension. In the first
example with lists, you're using literal syntax to construct (all at once) a
list. In this, you're using literal syntax to construct a generator-- the
generator is then passed to the list function, which iterates over it and
constructs a list, returning when that generator is exhausted.

And generator comprehensions don't leak their variables (I can't remember if
that was an implementation detail or a deliberate design decision, but
eventually list comprehensions were made to match the behavior).



> and 2)
>
> a=list([])
>
> vs.
>
> b=[[]]
>

Those are also doing two completely different things: on the first, you are
using literal syntax to create an empty list. You are then passing this list
(which is an iterable) to the list function, telling it to make a list out
of that literal. It does so, which is in the end a (shallow) copy of the
first list you made.

The second, you are using literal syntax to create an empty list, and using
literal syntax to place that empty list inside another list.

You basically can't treat the two things as interchangable, because they're
different: one is syntax, one is a function. Both are ways to make lists.

HTH,

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


Re: Questions about list-creation

2009-11-30 Thread inhahe
i should also mention that

a=[i for i in xrange(10)]

and

b=list(j for j in xrange(10))

isn't really just a difference of using [] vs. list()
the first case is a list comprehension, the second case is a generator
comprehension which is then converted to a list
(the bug only applies to list comprehensions, not generator comprehensions)

i.e. notice that you can do this
''.join(x for x in ['a','b','c'])
no list or [] involved - it's just a generator comprehension being
passed to a function.




On Mon, Nov 30, 2009 at 1:12 PM, inhahe  wrote:
> On Mon, Nov 30, 2009 at 12:22 PM, Manuel Graune  
> wrote:
>>
>> Hello,
>>
>> in (most) python documentation the syntax "list()"
>> and "[]" is treated as being more or less the same
>> thing. For example "help([])" and "help(list())" point
>> to the same documentation. Since there are at least
>> two cases where this similarity is not the case, (see below)
>> can someone explain the reasoning behind this and point to
>> further / relevant documentation?
>> (To clarify: I am not complaining about this, just asking.)
>>
>>
>> 1.)
>>
>> when using local variables in list comprehensions, say
>>
>> a=[i for i in xrange(10)]
>>
>> the local variable is not destroyed afterwards:
>>
>> print "a",a
>> print "i",i
>>
>> using the similar code
>>
>> b=list(j for j in xrange(10))
>>
>> the local variable is destroyed after use:
>>
>> print "b",b
>> print "j",j
>>
>
> I could be wrong, but I think this was actually a bug that was fixed later.
>
>> and 2)
>>
>> a=list([])
>>
>> vs.
>>
>> b=[[]]
>>
>
> those don't return the same thing
> list([]) will create a shallow copy of [], which will of course be []
>
> i can't think of a place where you'd want to use list() instead of [],
> but sometimes you might want to use 'list', such as in a defaultdict,
> in which case it's being used as a factory
>
>>
>> Regards,
>>
>> Manuel Graune
>>
>> --
>> A hundred men did the rational thing. The sum of those rational choices was
>> called panic. Neal Stephenson -- System of the world
>> http://www.graune.org/GnuPG_pubkey.asc
>> Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about list-creation

2009-11-30 Thread Mel
Manuel Graune wrote:

> in (most) python documentation the syntax "list()"
> and "[]" is treated as being more or less the same
> thing. For example "help([])" and "help(list())" point
> to the same documentation. Since there are at least
> two cases where this similarity is not the case, (see below)
> can someone explain the reasoning behind this and point to
> further / relevant documentation?
> (To clarify: I am not complaining about this, just asking.)
> 
> 
> 1.)
> 
> when using local variables in list comprehensions, say
> 
> a=[i for i in xrange(10)]
> 
> the local variable is not destroyed afterwards:
> 
> print "a",a
> print "i",i

Long ago, lists were built using explicit code:

a = []
for i in xrange(10):
a.append (i)

which of course left i bound to the last value that was appended.

People decided later that this was wordier than it had to be, and could bury 
the real point of a computation under a lot of boilerplate code that 
initialized lists, so we got list comprehensions, as you note, and they 
behave the same as the original code.

> using the similar code
> 
> b=list(j for j in xrange(10))
> 
> the local variable is destroyed after use:

The list constructor is a lot more recent.  It takes any iterable as an 
argument and makes (or tries to make) a list with the resulting values.  The 
example you give takes a sequence comprehension as its argument.  A sequence 
comprehension doesn't create data values -- it creates a block of code that 
can be executed later to create data values, and it can be executed later in 
any context.  So we could also code (untested):

def S():
return (j for j in xrange (10))

def T(s):
return list (s)

c = S()
b = T(c)

which still creates a list, but at an astonishing remove.  The sequence 
comprehension `c` can't count on finding a `j` in the namespace it finally 
gets executed in, so it has to have it's own private namespace to use then.

That's why you don't see `j` in your local namespace when `list` finallty 
runs the sequence comprehension.

Mel.


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


Re: Questions about list-creation

2009-11-30 Thread Lie Ryan

On 12/1/2009 4:22 AM, Manuel Graune wrote:


Hello,

in (most) python documentation the syntax "list()"
and "[]" is treated as being more or less the same
thing. For example "help([])" and "help(list())" point
to the same documentation. Since there are at least
two cases where this similarity is not the case, (see below)
can someone explain the reasoning behind this and point to
further / relevant documentation?
(To clarify: I am not complaining about this, just asking.)


1.)

when using local variables in list comprehensions, say

a=[i for i in xrange(10)]

the local variable is not destroyed afterwards:

print "a",a
print "i",i

using the similar code

b=list(j for j in xrange(10))

the local variable is destroyed after use:

print "b",b
print "j",j



It's not so much about list() vs. [] but generator comprehension vs. 
list comprehension. list() takes a generator comprehension, while 
[listcomp] is its own syntax. List comprehension leaked its "loop 
counter" to the surrounding namespace, while generator comprehension got 
its own tiny namespace.


This "bug" (or feature, depending on your political alignment) is fixed 
in Python 3.x:


Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> a = [i for i in range(10)]
>>> i
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'i' is not defined
>>> a = list(i for i in range(10))
>>> i
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'i' is not defined
>>> ^Z

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


Re: Questions about list-creation

2009-11-30 Thread inhahe
On Mon, Nov 30, 2009 at 12:22 PM, Manuel Graune  wrote:
>
> Hello,
>
> in (most) python documentation the syntax "list()"
> and "[]" is treated as being more or less the same
> thing. For example "help([])" and "help(list())" point
> to the same documentation. Since there are at least
> two cases where this similarity is not the case, (see below)
> can someone explain the reasoning behind this and point to
> further / relevant documentation?
> (To clarify: I am not complaining about this, just asking.)
>
>
> 1.)
>
> when using local variables in list comprehensions, say
>
> a=[i for i in xrange(10)]
>
> the local variable is not destroyed afterwards:
>
> print "a",a
> print "i",i
>
> using the similar code
>
> b=list(j for j in xrange(10))
>
> the local variable is destroyed after use:
>
> print "b",b
> print "j",j
>

I could be wrong, but I think this was actually a bug that was fixed later.

> and 2)
>
> a=list([])
>
> vs.
>
> b=[[]]
>

those don't return the same thing
list([]) will create a shallow copy of [], which will of course be []

i can't think of a place where you'd want to use list() instead of [],
but sometimes you might want to use 'list', such as in a defaultdict,
in which case it's being used as a factory

>
> Regards,
>
> Manuel Graune
>
> --
> A hundred men did the rational thing. The sum of those rational choices was
> called panic. Neal Stephenson -- System of the world
> http://www.graune.org/GnuPG_pubkey.asc
> Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Questions about list-creation

2009-11-30 Thread Manuel Graune

Hello,

in (most) python documentation the syntax "list()"
and "[]" is treated as being more or less the same
thing. For example "help([])" and "help(list())" point
to the same documentation. Since there are at least
two cases where this similarity is not the case, (see below)
can someone explain the reasoning behind this and point to
further / relevant documentation?
(To clarify: I am not complaining about this, just asking.)


1.)

when using local variables in list comprehensions, say

a=[i for i in xrange(10)]

the local variable is not destroyed afterwards:

print "a",a
print "i",i

using the similar code

b=list(j for j in xrange(10))

the local variable is destroyed after use:

print "b",b
print "j",j

and 2)

a=list([])

vs.

b=[[]]


Regards,

Manuel Graune

-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem about list indexing

2006-11-26 Thread John Machin
Steven D'Aprano wrote:
> On Sun, 26 Nov 2006 00:25:13 -0800, hollowspook wrote:
>
> > Hi, there
> >
> > a = range(100)
> >
> > if I want to use No 7, 11, 56,90 in a, then the only way I do is [a[7],
> > a[11], a[56], a[90]].
> > Is there any other way?
>
> a = [7, 11, 56, 90]
>
> Are those numbers supposed to be in some sort of series? They aren't an
> arithmetic series:
>
> (11 - 7) = 4
> (56 - 11) = 45  # not a constant difference
>
> nor are they a geometric series:
>
> (11/7) = 1.57
> (56/11) = 5.09  # not a constant ratio
>
> They don't look like some form of a Fibonacci series:
>
> 7+11 != 56
> 11+56 != 90
>
> If they're just "random" numbers, plucked out of thin air, then you
> probably can't calculate them and you'll need to just create them in a
> list a = [7, 11, 56, 90].
>

Actually, it's a cubic polynomial ;-)

| >>> def f(x):
| ... return (
| ... 7
| ... + 4 * x
| ... + 41 * x * (x - 1) // 2
| ... - 52 * x * (x - 1) * (x - 2) // 6
| ... )
| ...
| >>> [f(x) for x in range(4)]
|  [7, 11, 56, 90]

HTH,
John

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


Re: problem about list indexing

2006-11-26 Thread ZeD
hollowspook wrote:

> how about indexing 1-7, 10
> [range(1:8),10] will generate [[1, 2, 3, 4, 5, 6, 7], 10], instead of
> [1, 2, 3, 4, 5, 6, 7, 10]

>>> range(1,8)+[10]
[1, 2, 3, 4, 5, 6, 7, 10]

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


Re: problem about list indexing

2006-11-26 Thread hollowspook
Thanks, bearophile.
range(1, 8) + [10] is great!

"[EMAIL PROTECTED] 写道:
"
> hollowspook:
> > how about indexing 1-7, 10
> > [range(1:8),10] will generate [[1, 2, 3, 4, 5, 6, 7], 10], instead of
> > [1, 2, 3, 4, 5, 6, 7, 10]
>
> (Note that range(1:8) is a syntax error).
>
> You can join and extend lists as you like:
>
> >>> range(1, 8) + [10]
> [1, 2, 3, 4, 5, 6, 7, 10]
>
> See also the list.append and list.extend methods too.
> 
> Bye,
> bearophile

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

Re: problem about list indexing

2006-11-26 Thread bearophileHUGS
hollowspook:
> how about indexing 1-7, 10
> [range(1:8),10] will generate [[1, 2, 3, 4, 5, 6, 7], 10], instead of
> [1, 2, 3, 4, 5, 6, 7, 10]

(Note that range(1:8) is a syntax error).

You can join and extend lists as you like:

>>> range(1, 8) + [10]
[1, 2, 3, 4, 5, 6, 7, 10]

See also the list.append and list.extend methods too.

Bye,
bearophile

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

Re: problem about list indexing

2006-11-26 Thread hollowspook
Thanks, John

how about indexing 1-7, 10
[range(1:8),10] will generate [[1, 2, 3, 4, 5, 6, 7], 10], instead of
[1, 2, 3, 4, 5, 6, 7, 10]


"John Machin 写道:
"
> hollowspook wrote:
> > Hi, there
> >
> > a = range(100)
> >
> > if I want to use No 7, 11, 56,90 in a, then the only way I do is [a[7],
> > a[11], a[56], a[90]].
> > Is there any other way?
> >
>
> I presume a = range(100) is just an indication that a is a list -- the
> literal answer to your question as asked is simply [7, 11, 56, 90]
>
> In the general case that a is *any* list (or anything else that
> supports the index protocol, e.g. a string, a tuple, an array.array
> instance, or some instance of a so-written class), you can use a "list
> comprehension". Example:
>
> | >>> a = 'qwertyuiopasdfghjklzxcvbnm'
> | >>> [a[x] for x in [25, 0, 13, 1]]
> | ['m', 'q', 'f', 'w']
>
> Do try and find "list comprehension" in the manual and in your book or
> tutorial. It's useful for much more than the above.
> 
> HTH,
> John

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

Re: problem about list indexing

2006-11-26 Thread Steven D'Aprano
On Sun, 26 Nov 2006 00:25:13 -0800, hollowspook wrote:

> Hi, there
> 
> a = range(100)
> 
> if I want to use No 7, 11, 56,90 in a, then the only way I do is [a[7],
> a[11], a[56], a[90]]. 
> Is there any other way?

a = [7, 11, 56, 90]

Are those numbers supposed to be in some sort of series? They aren't an
arithmetic series:

(11 - 7) = 4
(56 - 11) = 45  # not a constant difference

nor are they a geometric series:

(11/7) = 1.57
(56/11) = 5.09  # not a constant ratio

They don't look like some form of a Fibonacci series:

7+11 != 56
11+56 != 90

If they're just "random" numbers, plucked out of thin air, then you
probably can't calculate them and you'll need to just create them in a
list a = [7, 11, 56, 90].



-- 
Steven.

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


Re: problem about list indexing

2006-11-26 Thread John Machin
hollowspook wrote:
> Hi, there
>
> a = range(100)
>
> if I want to use No 7, 11, 56,90 in a, then the only way I do is [a[7],
> a[11], a[56], a[90]].
> Is there any other way?
>

I presume a = range(100) is just an indication that a is a list -- the
literal answer to your question as asked is simply [7, 11, 56, 90]

In the general case that a is *any* list (or anything else that
supports the index protocol, e.g. a string, a tuple, an array.array
instance, or some instance of a so-written class), you can use a "list
comprehension". Example:

| >>> a = 'qwertyuiopasdfghjklzxcvbnm'
| >>> [a[x] for x in [25, 0, 13, 1]]
| ['m', 'q', 'f', 'w']

Do try and find "list comprehension" in the manual and in your book or
tutorial. It's useful for much more than the above.

HTH,
John

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


problem about list indexing

2006-11-26 Thread hollowspook
Hi, there

a = range(100)

if I want to use No 7, 11, 56,90 in a, then the only way I do is [a[7],
a[11], a[56], a[90]]. 
Is there any other way?

Thanks in advance.

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

Re: A question about list

2006-10-17 Thread Larry Bates
Larry Bates wrote:
> [EMAIL PROTECTED] wrote:
>> Hello:
>> Variable 'a' has the next values:
>> [[1,1],[2,2]]
>> and I want to take a to b as:
>> [[1,1,'='],[2,2,'=']]
>> How can I do this with only one line of instruction?
>> Thanks!!
>>
> To copy a list use:
> 
> b=a[:]
> 
> -Larry
Seems I may have misunderstood the question, but others
have answered appropriately.

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


Re: A question about list

2006-10-17 Thread rzed
[EMAIL PROTECTED] wrote in news:1161102973.920895.141500
@i42g2000cwa.googlegroups.com:

> Hello:
> Variable 'a' has the next values:
> [[1,1],[2,2]]
> and I want to take a to b as:
> [[1,1,'='],[2,2,'=']]
> How can I do this with only one line of instruction?
> Thanks!!
> 

b = [[x,y,'='] for (x,y) in a]

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


Re: A question about list

2006-10-17 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Hello:
> Variable 'a' has the next values:
> [[1,1],[2,2]]
> and I want to take a to b as:
> [[1,1,'='],[2,2,'=']]
> How can I do this with only one line of instruction?

b = [item + ['='] for item in a]

-- 
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: A question about list

2006-10-17 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> Hello:
> Variable 'a' has the next values:
> [[1,1],[2,2]]
> and I want to take a to b as:
> [[1,1,'='],[2,2,'=']]
> How can I do this with only one line of instruction?
> Thanks!!
> 
To copy a list use:

b=a[:]

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


Re: A question about list

2006-10-17 Thread Gerard Flanagan

[EMAIL PROTECTED] wrote:
> Hello:
> Variable 'a' has the next values:
> [[1,1],[2,2]]
> and I want to take a to b as:
> [[1,1,'='],[2,2,'=']]
> How can I do this with only one line of instruction?
> Thanks!!

>>> a = [[1,1], [2,2]]
>>> map( lambda x: x + ['='], a )
[[1, 1, '='], [2, 2, '=']]
>>>

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


A question about list

2006-10-17 Thread pretoriano_2001
Hello:
Variable 'a' has the next values:
[[1,1],[2,2]]
and I want to take a to b as:
[[1,1,'='],[2,2,'=']]
How can I do this with only one line of instruction?
Thanks!!

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


Re: about list

2005-11-20 Thread Jeffrey Schwab
[EMAIL PROTECTED] wrote:
> Shi Mu wrote:
> 
>>How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
>>Thanks!
> 
> 
> You want [[1,2],[1,4],[2,4]]?  That is, all combinations of 2 items
> from
> the list?  You might want to look at:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465
> 
> 
import * from xpermutations
[x for x in UniqueCombinations ([1,2,4], 2)]
> 
> [[1, 2], [1, 4], [2, 4]]
> 
> That web page also gives urls to other recipies that do the same thing.

Dang, that's better than my version.

$ ./combinations.py 2 1 2 4
[['1', '2'], ['1', '4'], ['2', '4']]

def combinations( universe, n=None ):

 """
 Return all possible combinations of length "n," where the
 elements of each combination are taken from the list "universe."
 """

 result = []

 if n == None:
 n = len( universe )

 if n > len( universe ):
 # No combination of elements can have cardinality
 # greater than universe, which is by definition the list
 # of all possible elements.
 pass
 elif n < 0:
 # No combination can have negative cardinaltiy.
 pass
 elif n == 0:
 # Only the empty combination has cardinality 0.
 result.append( [ ] )
 else:   # 0 < n <= len( universe )
 for i in xrange( len( universe ) ):
 elem = universe[i]
 post = universe[i+1:]
 for c in combinations( post, n - 1 ):
 choice = [ elem ]
 choice.extend( c )
 result.append( choice )

 return result

if __name__ == "__main__":

 import sys

 if len( sys.argv ) < 2:
 sys.stderr.write(
 "usage: %s  [elements ...]\n" % sys.argv[0] )
 sys.exit(1)

 n = int( sys.argv[1] )
 print repr( combinations( sys.argv[2:], n ) )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about list

2005-11-20 Thread rurpy

Shi Mu wrote:
> How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
> Thanks!

You want [[1,2],[1,4],[2,4]]?  That is, all combinations of 2 items
from
the list?  You might want to look at:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465

>>> import * from xpermutations
>>> [x for x in UniqueCombinations ([1,2,4], 2)]
[[1, 2], [1, 4], [2, 4]]

That web page also gives urls to other recipies that do the same thing.

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


Re: about list

2005-11-20 Thread Adonis
Shi Mu wrote:
> How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
> Thanks!

 From what I gather try:

a = [1,2,4]
n = list()
for i in a:
 index = a.index(i) + 1
 for x in a[index:]:
 n.append([i, x])
print n

more elegant ways to do this, but its a start.
hope this helps.

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


Re: about list

2005-11-20 Thread [EMAIL PROTECTED]
try to describe what you want as it is not very obvious, and has syntax
error.

Shi Mu wrote:
> How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
> Thanks!

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


about list

2005-11-20 Thread Shi Mu
How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list