【问题标题】:isinstance() method python returning wrong values [duplicate]isinstance()方法python返回错误值[重复]
【发布时间】:2017-10-24 06:45:39
【问题描述】:
list_d = ["a","b","c",3,5,4,"d","e","f",1,"ee"]
list_e = []

print("Before: %s"%(list_d))
print("Before: %s"%(list_e))

for item in list_d:
    if isinstance(item,int):
        list_d.pop(item)
        list_e.append(item)

print("After: %s"%(list_d))
print("After: %s"%(list_e))

我有这个代码。我想将list_d中的那些数字转移到list_e,但结果是:

Before: ['a', 'b', 'c', 3, 5, 4, 'd', 'e', 'f', 1, 'ee']
Before: []
After: ['a', 'c', 5, 'd', 'e', 'f', 1, 'ee']
After: [3, 4, 1]

不知何故 5 和 1 没有弹出,并且 1 附加到 list_e 但 5 没有。我的代码有什么问题?

【问题讨论】:

  • 您不应该在迭代列表时更改它。循环不知道您正在从中弹出项目,因此会产生令人困惑的输出。
  • 另请注意,pop(x) 会弹出 index x 处的项目
  • 为什么不直接使用filter(..., ...)

标签: python isinstance


【解决方案1】:

您在迭代列表时正在修改它。您可以只使用列表理解来制作两个列表,但我会首先研究为什么您有一个多类型列表

non_ints = [not isinstance(a, int) for a in list_d]
ints = [isinstance(a, int) for a in list_d]

或作为单一的交互版本

non_ints = []
ints = []

for a in list_d:
    if isinstance(a, int):
         ints.append(a)
    else:
         non_ints.append(a)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多