遍历列表元素以替换每个元素中的字符串

Looping through list elements to replace strings in each element

我有一份大学名单:

['1 1  LOMONOSOV MOSCOW STATE UNIVERSITY  XL FO VH  5  A  100 100 100  87.1            52.4 52  99.3 87  100 100', '', '', '', ''],
['2 2 NOVOSIBIRSK STATE UNIVERSITY                                                 M CO VH 98.1 96.5 88.9 98.8 59.7 38.1 69.8 92.1 99.4 96.7', '', '', '', ''],
...

我想删除多余的信息(nrs、空格...),只保留大学名称。

为此,我试图遍历我的列表,用“”替换数字和其他不需要的字符。

到目前为止我有:

for i in range(len(flat_data2)):

    mainString = flat_data2[i]

    def replaceMultiple(mainString, unwanted, input_char):
    # Iterate over the strings to be replaced
        for elem in unwanted :
        # Check if string is in the main string
            if elem in mainString :
            # Replace the string
                mainString = mainString.replace(elem, input_char)

        return  mainString
replaceMultiple(mainString, unwanted, input_char)

不幸的是,我只返回了列表的最后一个元素(尽管删除了不需要的字符...)。

我错过了什么?或者你有更好的解决方案吗? 非常感谢!

你可以试试:

input_char = ""
conv = ''.maketrans({c: input_char for c in unwanted})

l = list()   # if you want a list of all your strings
for i in range(len(flat_data2)):
    mainString = flat_data2[i].translate(conv)
    l.append(mainString)

您的问题来自这样一个事实,即您在每次循环迭代中都继续定义函数,但您没有 运行 它或保存它的输出。使它起作用的最小更改是:

def replaceMultiple(s, unwanted, input_char):
    # Iterate over the strings to be replaced
    for elem in unwanted:
        # Replace the string, does not do anything if `elem` not in `s`
        s = s.replace(elem, input_char)
    return s

flat_data2_new = [replaceMultiple(x) for x in flat_data2]