This commit is contained in:
2017-02-23 11:11:38 -05:00
+14 -1
View File
@@ -787,6 +787,11 @@ full string is needed. One thing to notice, however, is that list
comprehensions are better and faster than constructing a list in a loop comprehensions are better and faster than constructing a list in a loop
with calls to ``append()``. with calls to ``append()``.
One other option is using the map function, which can 'map' a function
('str') to an iterable ('range(20)'). This results in a map object,
which you can then ('join') together just like the other examples.
The map function can be even faster than a list comprehension in some cases.
**Bad** **Bad**
.. code-block:: python .. code-block:: python
@@ -807,7 +812,7 @@ with calls to ``append()``.
nums.append(str(n)) nums.append(str(n))
print "".join(nums) # much more efficient print "".join(nums) # much more efficient
**Best** **Better**
.. code-block:: python .. code-block:: python
@@ -815,6 +820,14 @@ with calls to ``append()``.
nums = [str(n) for n in range(20)] nums = [str(n) for n in range(20)]
print "".join(nums) print "".join(nums)
**Best**
.. code-block:: python
# create a concatenated string from 0 to 19 (e.g. "012..1819")
nums = map(str, range(20))
print "".join(nums)
One final thing to mention about strings is that using ``join()`` is not always One final thing to mention about strings is that using ``join()`` is not always
best. In the instances where you are creating a new string from a pre-determined best. In the instances where you are creating a new string from a pre-determined
number of strings, using the addition operator is actually faster, but in cases number of strings, using the addition operator is actually faster, but in cases