替换2d python列表中的字符串

时间:2017-07-09 06:40:27

标签: python string list loops

我在文本文件中读取行,然后用空格分割这些行,给我一个2d列表。嵌入式数组中的某些字符串包含我尝试使用str.replace过滤掉的垃圾,但它无效。

import os

infile = 'CMULEX.txt'

data = []
with open(infile, 'r') as f:
    read_data = f.readlines()

    for row in read_data[:5]:
        split_line = (row.split())
        data.append(split_line)

for line in data[:5]:
    for wd in line:
        wd = wd.replace('Coda', '')

2 个答案:

答案 0 :(得分:1)

wd是一个局部变量。它不是"指针"回到列表。列表理解似乎是一个优雅的解决方案:

for row in read_data[:5]:
    split_line = (row.split())
    data.append([wd.replace("Coda", "") for wd in split_line])

答案 1 :(得分:-1)

For line in data[:5]:
   line[:] = [ '' if x == 'Coda' else x for x in line]