简体   繁体   English

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

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

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

You haven't initialised phrase (The list you were intending to make) into a variable yet. 您还没有将phrase (您打算制作的list初始化为变量。 So pretty much you have created a list in each loop, it being the exact same. 所以你几乎已经在每个循环中创建了一个列表,它完全相同。

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. 也许make phraselist = list(phrase) ,然后编辑for循环中的列表。 Also, you can use range() : 此外,您可以使用range()

>>> phrase = "hello"
>>> phraselist = list(phrase)
>>> for i in range(1,4):
...     phraselist[i] = phraselist[i].upper()
... 
>>> print ''.join(phraselist)
hELLo
>>> 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'

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

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

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

list() creates a new list. list()创建一个列表。 Your loop creates and instantly discards two new lists on each iteration. 你的循环创建并立即丢弃每次迭代的两个新列表。 You could write it as: 你可以把它写成:

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 bytearray which is mutable: 或者,如果您正在处理字节串,您可以使用可变的bytearray

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM