【问题标题】:Replacing an item in a python list by index.. failing?用索引替换python列表中的项目..失败?
【发布时间】:2013-05-30 17:47:54
【问题描述】:

知道为什么当我打电话时:

>>> hi = [1, 2]
>>> hi[1]=3
>>> print hi
[1, 3]

我可以通过索引更新列表项,但是当我调用时:

>>> phrase = "hello"
>>> for item in "123":
>>>     list(phrase)[int(item)] = list(phrase)[int(item)].upper()
>>> print phrase
hello

失败了?

应该是hELLo

【问题讨论】:

    标签: python list python-2.7 indexing


    【解决方案1】:

    您尚未将phrase(您打算创建的list)初始化为变量。所以几乎你已经在每个循环中创建了一个列表,它是完全相同的。

    如果您打算实际更改 phrase 的字符,那是不可能的,因为在 python 中,字符串是不可变的。

    也许制作phraselist = list(phrase),然后在for循环中编辑列表。另外,你可以使用range():

    >>> phrase = "hello"
    >>> phraselist = list(phrase)
    >>> for i in range(1,4):
    ...     phraselist[i] = phraselist[i].upper()
    ... 
    >>> print ''.join(phraselist)
    hELLo
    

    【讨论】:

      【解决方案2】:
      >>> phrase = "hello"
      >>> list_phrase = list(phrase)
      >>> for index in (1, 2, 3):
              list_phrase[index] = phrase[index].upper()
      >>> ''.join(list_phrase)
      'hELLo'
      

      如果您更喜欢单线:

      >>> ''.join(x.upper() if index in (1, 2, 3) else x for
                  index, x in enumerate(phrase))
      'hELLo'
      

      【讨论】:

      • 还有个没用的list(phrase)
      【解决方案3】:

      考虑到字符串在python中是不可变的你不能修改现有的字符串可以创建新的。

      ''.join([c if i not in (1, 2, 3) else c.upper() for i, c in enumerate(phrase)])

      【讨论】:

        【解决方案4】:

        另一个答案,只是为了好玩:)

        phrase = 'hello'
        func = lambda x: x[1].upper() if str(x[0]) in '123' else x[1]
        print ''.join(map(func, enumerate(phrase)))
        # hELLo
        

        为了使它更健壮,我创建了一个方法:(因为我很棒,而且很无聊)

        def method(phrase, indexes):
            func = lambda x: x[1].upper() if str(x[0]) in indexes else x[1]
            return ''.join(map(func, enumerate(phrase)))
        
        print method('hello', '123')
        # hELLo
        

        【讨论】:

        • 因为使用列表推导太主流了
        • 究竟什么是“非pythonic”?
        【解决方案5】:

        list() 创建一个 列表。您的循环在每次迭代中创建并立即丢弃两个新列表。你可以写成:

        phrase = "hello"
        L = list(phrase)
        L[1:4] = phrase[1:4].upper()
        print("".join(L))
        

        或者没有列表:

        print("".join([phrase[:1], phrase[1:4].upper(), phrase[4:]]))
        

        字符串在 Python 中是不可变的,因此要更改它,您需要创建一个新字符串。

        或者,如果您正在处理字节串,您可以使用可变的bytearray

        phrase = bytearray(b"hello")
        phrase[1:4] = phrase[1:4].upper()
        print(phrase.decode())
        

        如果索引不连续;您可以使用显式的 for 循环:

        indexes = [1, 2, 4]
        for i in indexes:
            L[i] = L[i].upper()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-31
          • 2021-04-14
          • 1970-01-01
          • 2016-04-03
          相关资源
          最近更新 更多