How to replace values at specific indexes of a python list?

前端 未结 7 863
忘掉有多难
忘掉有多难 2020-12-05 03:59

If I have a list:

to_modify = [5,4,3,2,1,0]

And then declare two other lists:

indexes = [0,1,3,5]
replacements = [0,0,0,0]         


        
相关标签:
7条回答
  • 2020-12-05 05:00

    for index in a:

    This will cause index to take on the values of the elements of a, so using them as indices is not what you want. In Python, we iterate over a container by actually iterating over it.

    "But wait", you say, "For each of those elements of a, I need to work with the corresponding element of m. How am I supposed to do that without indices?"

    Simple. We transform a and m into a list of pairs (element from a, element from m), and iterate over the pairs. Which is easy to do - just use the built-in library function zip, as follows:

    for a_element, m_element in zip(a, m):
      s[a_element] = m_element
    

    To make it work the way you were trying to do it, you would have to get a list of indices to iterate over. This is doable: we can use range(len(a)) for example. But don't do that! That's not how we do things in Python. Actually directly iterating over what you want to iterate over is a beautiful, mind-liberating idea.

    what about operator.itemgetter

    Not really relevant here. The purpose of operator.itemgetter is to turn the act of indexing into something, into a function-like thing (what we call "a callable"), so that it can be used as a callback (for example, a 'key' for sorting or min/max operations). If we used it here, we'd have to re-call it every time through the loop to create a new itemgetter, just so that we could immediately use it once and throw it away. In context, that's just busy-work.

    0 讨论(0)
提交回复
热议问题