Function variable

[Inspired by this question ]

Suppose I have two lists:

list1 = ['tom', 'mary', 'frank', 'joe', 'john', 'barry']
list2 = [1, 2, 3, 4]

I want to match each name in list1with number in list2. Since list2there are four numbers in, I would like to associate each of the first four names with the corresponding number in list2and assign random numbers to the remaining names in list1.

I know that I can solve this problem using for-loop with enumerateand random.choice. Indeed, I provided such a solution to the original problem.
I would like to know, however, if you can do something like this:

for name, number in itertools.izip_longest(list1, list2, fillvalue=MAGIC):
    print name, number

I originally thought of using something like this:

MAGIC = random.choice(list1)

, random.choice(list1), fillvalue zipping. , , . , itertools.izip_longest fillvalue , , . , , , , . lambda .

, ? itertools.izip_longest fillvalue? __repr__ ? , __repr__, ?

+4
2

, , , 2:

def inf_gen(f):
    while True:
        yield f()

, inf_gen(f) iter(f, None), , f . iter , .

:

>>> from itertools import izip, chain
>>> for name, number in izip(list1,chain(list2, iter(lambda: random.choice(list2), None))):
    print name, number

tom 1
mary 2
frank 3
joe 4
john 1
barry 4

itertools, , itertools.count:

>>> from itertools import izip, chain, count
>>> for name, number in izip(list1, chain(list2, (random.choice(list2) for _ in count()))):
    print name, number
+8

"" , , http://docs.python.org/2.7/library/itertools.html?highlight=izip_longest#itertools.izip_longest

from itertools import repeat, chain, count

class ZipExhausted(Exception):
    pass

def izip_longest2(*args, **kwds):
    fillvalue = kwds.get('fillvalue')
    fillgen = kwds.get('fillgen', repeat(fillvalue))  # added
    counter = [len(args) - 1]
    def sentinel():
        if not counter[0]:
            raise ZipExhausted
        counter[0] -= 1
        yield next(fillgen)  # modified
    iterators = [chain(it, sentinel(), fillgen) for it in args]  # modified
    try:
        while iterators:
            yield tuple(map(next, iterators))
    except ZipExhausted:
        pass


a = ['bob', 'mary', 'paul']
b = ['eggs', 'spam']
c = ['a', 'b', 'c', 'd']

for x in izip_longest2(a, b, c, fillgen=count()):
    print '\t'.join(map(str, x))

# output:
# bob   eggs    a
# mary  spam    b
# paul  0   c
# 1 2   d
+3

Source: https://habr.com/ru/post/1525693/


All Articles