2014-07-03 26 views
0

我正在尝试编写一个程序的一部分,该程序需要先前生成的列表,其中列表中的所有项都是包含字母和数字的字符串,并将所有字母。For循环不会更改正在操作的变量

这是我写这样做代码:

test = ["test252k", "test253k"] 
numbers = list(str(range(0,10))) 

for i in test: 
    i = list(i) 
    i = [x for x in i if x in numbers] 
    i = "".join(str(e) for e in i) 
    test = [i for i in test] 

但是,当我打印测试,我刚刚得到线原始列表1.

我该怎么办,以保证for循环用新值替换i的原始值?

+0

你怎么想test'与'我要实现我? – Trilarion

+0

你为什么不简单地说:'''.join([如果不是x.isdigit()])这将从字符串中删除数字。对列表中的所有元素执行此操作。 – Maroun

+1

期望是[我在测试中]会用新值取代原始值,虽然看起来没有起作用,但我应该已经删除了它。 – joeqesi

回答

2

你真正的问题是你没有以任何方式更新test。当您执行[i for i in test]列表理解时,您使用i会隐藏外循环中声明的变量。如果i已更新的值,那么只需将它添加到一个新的列表:

new_list = [] 
for i in test: 
    i = list(i) 
    i = [x for x in i if x in numbers] 
    i = "".join(str(e) for e in i) 
    new_list.append(i) 
+0

这很好,谢谢 – joeqesi

0
test = ["test252k", "test253k"] 
    numbers = list(str(range(0,10))) 
    count = 0 
    for i in test: 
     i = list(i) 
     i = [x for x in i if x in numbers] 
     i = "".join(str(e) for e in i) 
     test[count] = i 
     count = count + 1 

    print test