通过索引替换python列表中的项目..失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16916013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:59:39  来源:igfitidea点击:

Replacing an item in a python list by index.. failing?

pythonlistpython-2.7indexing

提问by Jamus

Any idea why when I call:

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

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

I can update a list item by its index, but when I call:

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

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

It fails?

它失败?

Should be hELLo

应该 hELLo

回答by TerryA

You haven't initialised phrase(The listyou were intending to make) into a variable yet. So pretty much you have created a list in each loop, it being the exact same.

您尚未将phraselist您打算制作的)初始化为变量。因此,您几乎在每个循环中都创建了一个列表,它完全相同。

If you were intending to actually change the characters of phrase, well that's not possible, as in python, strings are immutable.

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

Perhaps make phraselist = list(phrase), then edit the list in the for-loop. Also, you can use range():

也许 make 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

回答by Mike Müller

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

If you prefer one-liner:

如果您更喜欢单线:

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

回答by oleg

consider that strings are immutable in python You can't modify existing string can create new.

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

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

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

回答by Inbar Rose

Another answer, just for fun :)

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

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


To make this robust, I created a method: (because I am awesome, and bored)

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

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

回答by jfs

list()creates a newlist. Your loop creates and instantly discards two new lists on each iteration. You could write it as:

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

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

Or without a list:

或者没有列表:

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

Strings are immutable in Python therefore to change it, you need to create a new string.

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

Or if you are dealing with bytestrings, you could use bytearraywhich is mutable:

或者,如果您正在处理字节串,则可以使用bytearraywhich 是可变的:

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

If indexes are not consecutive; you could use an explicit for-loop:

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

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