0

マップ内でループしたい。私のコードは次のようなものです:

for (abcID,bbbID) in map(abcIdList,bbbIdList):
        buildXml(abcID,bbbID)

これを機能させるにはどうすればよいですか?

4

2 に答える 2

4

ええと、代わりに欲しいと思いますzip()...

>>> zip((1, 2), ('a', 'b'))
[(1, 'a'), (2, 'b')]
于 2012-06-25T07:03:38.780 に答える
2

You mix up map() and zip() or dict().

map operates on iterables and takes two arguments, a function and an iterable:

>>> def addOne(x):
...     return x+1
... 
>>> l = [1, 2, 3, 4]
>>> print(map(addOne, l))
[2, 3, 4, 5]

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:

>>> l1, l2 = [1, 2, 3, 4], [5, 6, 7, 8]
>>> print(zip(l1, l2))
[(1, 5), (2, 6), (3, 7), (4, 8)]

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):

>>> d = dict(zip(l1, l2))
>>> d[1]
5
>>> d
{1: 5, 2: 6, 3: 7, 4: 8}

However, you can not directly iterate over key-value pairs in dicts:

>>> for key, value in d:
...   print(key)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

This is a rather obscure error message, as we passed a dict not an int! Where the heck does the int come from? By default, when iterating over a dict, one will iterate over the keys:

>>> list(d)
[1, 2, 3, 4]

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:

>>> for key, value in d.items():
...   print(key, value)
... 
1 5
2 6
3 7
4 8

(output might differ depending on whether you imported the print_function from __future__). For large dicts and on python2, iteritems() will be faster than items(), as items() puts all key-value pairs in a list first, while iteritems() creates only a lazy iterator. On python3, items() does something similar to that already.

I hope that clarifies the situation a bit.

于 2012-06-25T07:45:31.387 に答える