【问题标题】:For loop doesn't change the variable being operated on [duplicate]For循环不会改变正在操作的变量[重复]
【发布时间】:2014-08-24 16:56:26
【问题描述】:

我正在尝试编写一个程序的一部分,该程序接受先前生成的列表,其中列表中的所有项目都是包含字母和数字的字符串,并删除所有字母。

这是我为此编写的代码:

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 的原始值替换为新值?

【问题讨论】:

  • 你想用i for i in test实现什么?
  • 你为什么不干脆:''.join([x for x in str if not x.isdigit()])?这会从字符串中删除数字。对列表中的所有元素执行此操作。
  • 期望是 [i for i in test] 会用新值替换原始值,虽然看到它没有工作,我应该删除它。
  • @user3801997 你应该使用不同的变量名,以免陷入阴影i for i in whatever 在 Python 中什么都不做的陷阱。您的问题还有更简单的解决方案。查看答案。 :)
  • Maroun Maroun,我刚刚尝试使用您的代码,虽然它更简洁,但我仍然遇到同样的问题。

标签: python


【解决方案1】:

你真正的问题是你没有以任何方式更新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)

【讨论】:

  • 效果很好,谢谢
【解决方案2】:
    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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    相关资源
    最近更新 更多