Python has a module called itertools. As the name implies, iterator utilities can be a little useful to know. So make a note of what you think you can use, along with a personal code example. Python is 2.7. Since it is possible to write equivalently in the comprehension notation, I tried to summarize only those that seem to make the code concise. (There may be something that can be written more concisely. If so, please tell me secretly.)
(Actually, I made this memo because it was a little convenient to use chain this time)
from itertools import chain
#Example: a,I want to sum the fuga properties of each element of b
#no itertools used
hoge = sum(x.fuga for y in (a, b) for x in y)
#use
hoge = sum(x.fuga for x in chain(a, b))
from itertools import combinations
#Example:I want to loosen two different elements in array a
#Similarly, it can be used when you want to unravel different n elements.
#Not used
for i in xrange(len(a)):
for j in xrange(i + 1, len(a)):
hoge(a[i], a[j])
#Use (i<j is guaranteed)
for i, j in combinations(xrange(len(a)), 2):
hoge(a[i], a[j])
#Or
for a1, a2 in combinations(a, 2):
hoge(a1, a2)
I'm wondering whether itertools should be used or nested. Personally, I would definitely use itertools if the nesting is likely to be triple or more.
You can use product
if you want to combine different types of subscripts. For example, if you want hoge (a [i], b [j])
for i, j in product(xrange(len(a)), xrange(len(b))):
hoge(a[i], b[j])
#Or
for ea, eb in product(a, b):
hoge(ea, eb)
will do.
Use permutations
to distinguish betweenhoge (i, j)
andhoge (j, i)
.
If you want to count hoge (i, i)
, you can use product (xrange (len (a)), repeat = 2)
or product (a, repeat = 2)
.
It seems to be useful because I often have to write code that licks multiple lists like this personally.
from itertools import groupby
#Example:Show dict a key with the same value
#Not used
tmp = {}
for k, v in a.items():
if v in tmp:
tmp[v].append(k)
else:
tmp[v] = [k]
for k, v in tmp.items():
print "[%s] has value %s" % (' ,'.join(v), k)
#use
f = lambda k:a[k]
keys = sorted(a.keys(), key=f)
for k, v in groupby(keys, f):
print "[%s] has value %s" % (' ,'.join(v), k)
You have to sort it once.
Also, list (groupby (hoge))
is impossible.
It is repeat
. It might be nice to combine it with zip
.
Recommended Posts