简体   繁体   English

Python:查找特定列表项并替换

[英]Python: finding a particular list item and replacing

I tried to look for the solution to this question by perusing the forum but many of the explanations provided are too advanced for me and was wondering if there were a simpler method. 我试图通过浏览论坛来寻找解决此问题的方法,但是提供的许多解释对我来说太高级了,我想知道是否有更简单的方法。

So my question is: 所以我的问题是:

my_list = [1, 2, 3, 4, 5, 6]

In my_list , I would like to replace all even numbers with an "x". my_list ,我想用“ x”替换所有偶数。

Is there method where I can just go through a loop and replace them? 有没有一种方法可以循环替换它们?

Ok, so I was hoping there'd be a simple method like a my_list.replace function but realized there wasn't. 好的,所以我希望有一个简单的方法,例如my_list.replace函数,但意识到没有。 So here is the context in which I need to locate and replace: 因此,这是我需要查找和替换的上下文:

def censor(text, word):
    string = text.split()
    for n in range(len(string)):
        if string[n] == word:
            string[n] == "*" * len(word)

    return string

print censor("hi bob how are you bob", "bob")

So in this program I'm trying to replace the "bob" in the phrase to asterisks in accordance to the length of the word bob. 因此,在此程序中,我尝试根据单词bob的长度将短语中的“ bob”替换为星号。 But I am not sure what I'm doing wrong here. 但是我不确定我在做什么错。 Instead the output I'm getting is the same phrase. 相反,我得到的输出是相同的短语。 Thanks! 谢谢!

Use a list comprehension: 使用列表理解:

my_list = ['x' if i % 2 == 0 else i for i in my_list]

Yes, this still uses a loop, but you need to scan all values for the even numbers anyway . 是的,这仍然使用循环,但是无论如何您都需要扫描所有值的偶数。

If you don't want a list comprehension (if you wanted to have a more elaborate replacement at some point later) you could loop through it and edit each value in turn if necessary: 如果您不希望列表理解(如果您以后想要在某个位置进行更详尽的替换),则可以遍历列表并根据需要依次编辑每个值:

for i in range(len(my_list)):
    if not my_list[i] % 2:
        my_list[i] = 'x'

It's not as clean as a comprehension though. 但是,这不像理解力那么干净。

To "just go through the loop and replace them", you could use: 要“只需遍历循环并替换它们”,可以使用:

for index, item in enumerate(my_list):
    if not item % 2:
        my_list[index] = "x"

A list comprehension is neater, but will build a new list rather than modifying the old one - which you need will depend on what you are doing. 列表理解比较整洁,但是会建立一个新列表而不是修改旧列表-您需要的取决于您的工作。

为了提供另一种选择,我们还可以使用map

map(lambda n: 'x' if n%2==0 else n, my_list)

This is the most concise: 这是最简洁的:

map(lambda i: 'x' if i % 2 ==0 else i, my_list)

Out[17]: [1, 'x', 3, 'x', 5, 'x'] Out [17]:[1,'x',3,'x',5,'x']

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

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