On Tue, 9 Mar 2010 11:25:19 +0800
Joson <[email protected]> wrote:
> if labels is None: labels = [OrderedSet() for _ in xrange(ndim)]
> ......
>
> It's a library named "divisi". "OrderedSet" is a string set defined in this
> lib. "ndim" is integer. What's the meaning of "for _ in" ?
>
> Joson
[OrderedSet() for _ in xrange(n)]
builds a list of ndim empty ordered sets. '_' is the index, but is unused; '_'
is commonly used as required, but unused, variable name (not only in python).
This is just a tricky python idiom, because there is no builtin syntax to do
this.
[OrderedSet()] * ndim
would build a list with ndim times the *same* set, so that if one item is
changed, all are changed. The above syntax instread creates *distinct* sets.
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> lists = [list()] *3
>>> lists
[[], [], []]
>>> list1 = lists[1]
>>> list1.append('*')
>>> lists
[['*'], ['*'], ['*']]
>>> lists = [list() for _ in range(3)] # _ is unused
>>> lists
[[], [], []]
>>> list1 = lists[1]
>>> list1.append('*')
>>> lists
[[], ['*'], []]
>>> lists = [list()] * 3
>>> for i in range(len(lists)) : lists[i].append(i)
...
>>> lists
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
>>> lists = [list() for i in range(3)]
>>> for i in range(len(lists)) : lists[i].append(i)
...
>>> lists
[[0], [1], [2]]
Denis
--
________________________________
la vita e estrany
spir.wikidot.com
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor