I want to do a loop in a map. My code is like this:
for (abcID,bbbID) in map(abcIdList,bbbIdList):
buildXml(abcID,bbbID)
How should I do to make this work?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You mix up
map()andzip()ordict().mapoperates on iterables and takes two arguments, a function and an iterable:So it applies the function passed as first argument to each element of the sequence and returns the new sequence as list (note that this behaviour is different in python3, where you get an iterable instead of a list).
zip()instead does what you want. It takes an arbitary amount of iterables and merges together each iteration step to one tuple:Again, the result value is a list in python2 and an iterator in python3. You can iterate over that using a normal for loop like you did in your question. Of such a zipped iterator you can also create a
dict(which might also be called a map, as it maps items to values):However, you can not directly iterate over key-value pairs in dicts:
This is a rather obscure error message, as we passed a
dictnot anint! Where the heck does theintcome from? By default, when iterating over adict, one will iterate over the keys:But we instructed python to do unpacking on our values. So it tries to get two values out of one int, which obviously does not work. In that light, the error seems reasonable. So to iterate over key-value pairs one has to use:
(output might differ depending on whether you imported the
print_functionfrom__future__). For large dicts and on python2,iteritems()will be faster thanitems(), asitems()puts all key-value pairs in a list first, whileiteritems()creates only a lazy iterator. On python3,items()does something similar to that already.I hope that clarifies the situation a bit.