简体   繁体   English

python中列表的修改函数和替换字符串

[英]Modifying functions of lists and replacing strings in python

There are two skeleton examples after the function code, called "pets" and "movies" function代码后有两个骨架例子,分别称为“宠物”和“电影”

Need help with my code below because errors keep popping up.需要帮助我的代码如下,因为错误不断弹出。

The code:编码:

def cleaner(list1):
    for ele in list1:
        if ele == ['a']['the']['and']:
        print('X')



movies = ["I","watched","a","funny","and","good","movie"]
cleaner(movies)
print(movies)
  1. Your if ele == ['a']['the']['and']: means nothing, how a variable could be equal to 3 lists with ones items each?你的if ele == ['a']['the']['and']:没有任何意义,一个变量怎么可能等于 3 个列表,每个列表都有一个项目? (that syntax doesn't even exists (该语法甚至不存在

  2. You don't replace anything, you're just printing, your need to change the value inside the list你不替换任何东西,你只是在打印,你需要更改列表中的值


Here the fix, that modifies inplace the list这里的修复,修改就地list

def cleaner(list1):
    for i, ele in enumerate(list1):
        if ele in ['a', 'the', 'and']:
            list1[i] = 'X'

pets = ["the", "dog", "and", "a", "cat"]
cleaner(pets)
print(pets)

Here the version that returns a new list, and so require assignement on output这里返回新列表的版本,因此需要在 output 上分配

def cleaner(list1):
    blacklist = ['a', 'the', 'and']
    return ['X' if x in blacklist else x for x in list1]

pets = ["the", "dog", "and", "a", "cat"]
pets = cleaner(pets)
print(pets)
def cleaner(list1):
    for ele in list1:
        if ele == ['a']['the']['and']:
        print('X')

The problem is with your if statement.问题在于您的 if 语句。 You have to check each case separately.您必须分别检查每个案例。

if ele=="a" or ele=="the" or ele=="and":

Because what you did there is not a valid Python expression.因为您所做的不是有效的 Python 表达式。

If you want to modify the contents of a list of immutable objects (strings are immutable in python), you need to do something different than for ele in list .如果要修改不可变对象列表的内容(字符串在 python 中是不可变的),则需要执行与for ele in list不同的操作。 because changing ele will not actually change the contents of the list.因为改变ele实际上不会改变列表的内容。 (Although, you are not even doing that, you're just printing "X", but I assume that's what you want to do). (虽然,你甚至没有这样做,你只是打印“X”,但我认为这就是你想要做的)。 You can do this instead, which will modify the list in-place:您可以改为这样做,这将就地修改列表:

def cleaner(list1):
    for i in range(len(list1)):
        if list1[i] in ['a', 'the', 'and']:
            list1[i] = 'X'

pets = ["the","dog","and","a","cat"]
cleaner(pets)

Or, an even more elegant approach:或者,更优雅的方法:


def cleaner(item):
    if item in ['a', 'the', 'and']:
        return 'X'
    else:
        return item


pets = ["the","dog","and","a","cat"]
cleaned_pets = list(map(cleaner, pets))

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

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