I have two generators lists:
letters= ('AA', 'AB',...,'AZ)
digits= (0,1,2,3,...,9)
From letters and digits, I would like to obtain a third generator list (names)
, so that:
names= ('AA0', 'AA1'.., 'AA9', 'AB0',..'AB9',...'AZ0',...,'AZ9')
. I've tried for a couple of days to achieve 'names' with itertools
functions but I cannot achieve the desired result.
The last thing I tried was:
'''
names= dict((key, digits) for key in letters)
def naming():
for key in names.keys():
for dig in names.values():
yield(''.join('{}{}'.format(key, dig)))
names= ('{}{}'.format(key, value) for key, value in names.items())
'''
But it doesn't work, and I definitely want a generator list.
Thank you for your help.
Use itertools.product
:
from itertools import product
letters = ("AA", "AB")
digits = (0,9)
["".join(p) for p in product(letters, map(str, digits))]
Output:
['AA0', 'AA9', 'AB0', 'AB9']
What's wrong in this snippet is iterating over names.values()
in inner loop.
>>> let=['a','b','c']
>>> dig=[1,2,3]
>>> nms=dict((key, dig) for key in let)
>>> nms
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
>>> nms.values()
dict_values([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
You should rewrite it as
def fn():
for k in nms.keys():
for d in nms[k]:
yield(''.join('{}{}'.format(k,d)))
list(fn())
# ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.