【问题标题】:Python 2.6:Trying to run an if statement if variable is a list [duplicate]Python 2.6:如果变量是列表,则尝试运行 if 语句 [重复]
【发布时间】:2020-12-15 06:39:32
【问题描述】:

我是 python 新手,正在尝试完成一个练习,我打印列表中的每个变量,包括任何嵌套列表。

我的问题是我无法让嵌套列表被 if 语句识别为列表。

当我运行 type(i) 时,它返回它是一个列表,但是当我运行 if type(i) is listif type(i) == list 时它无法执行。

当我尝试使用 if isinstance(type(i), list) 时,我得到一个 TypeError:isinstance() arg 2 must be a class, type, or tuple of classes and types.

当我尝试isinstance(type(i),collections.Sequence) 时,嵌套列表也不被识别为列表。

如果有人有任何建议,我们将不胜感激。我正在使用 Python 2.6,因为我正在学习 MIT 课程。

谢谢

# -*- coding: cp1252 -*-
import collections

listval= ["war",1,["brie","rocky","roq le coq"],[1,2,3]]

def printlist2(lists):
    for i in lists:
        print("Variable value: ", type(i))
        print ("Is variable a list: ",isinstance(type(i),collections.Sequence))
        #print (isinstance(type(i),list))
        if isinstance(type(i),collections.Sequence):
            print ("This is a list")
            printlist2(i)
        elif type(i) == list:
            print ("This is a list")
        elif type(i) is int:
            #print ("String length is equal to ",len(str(i)))
            print ("i is equal to integer ",i)
        else:
            #print ("String length is equal to ",len(i))
            print ("i is equal to string ",i) 

printlist2(listval)

【问题讨论】:

  • 使用实例时不需要type()
  • 如果您是 python 新手,请不要从 python 2.6 开始。 Python 2 已于去年结束。使用 3.8 或 3.9 等最新版本。

标签: python python-2.6


【解决方案1】:

有多种测试列表的方法。尝试一次使用所有这些确实是令人困惑和不必要的,尤其是在这样的论坛中提出问题时。我建议使用isinstance。您只想针对对象本身进行测试,而不是将其 type()isinstance 一起使用

如果您使用该测试或其中一种替代方法,您的代码结构可以正常工作,并且您会在运行期间得到准确的 2 个列表。您的输入数据没有很好地展示递归,但如果您添加更多级别的嵌入式列表,代码将处理它。这是代码的简化版本,表明使用 isinstance 确实有效:

# -*- coding: cp1252 -*-

listval= ["war",1,["brie","rocky","roq le coq"],[1,2,3]]

def printlist2(lists):
    for i in lists:
        if isinstance(i, list):
            print ("This is a list: " + str(i))
            printlist2(i)
        else:
            print ("This is not a list: " + str(i))

printlist2(listval)

结果:

This is not a list: war
This is not a list: 1
This is a list: ['brie', 'rocky', 'roq le coq']
This is not a list: brie
This is not a list: rocky
This is not a list: roq le coq
This is a list: [1, 2, 3]
This is not a list: 1
This is not a list: 2
This is not a list: 3

type(i) == list1type(i) is list 也可以。随便挑一个。此代码适用于 Python 2 和 Python 3。我同意 @Wombatz - 使用最新版本的 Python 3。

【讨论】:

    猜你喜欢
    • 2015-02-03
    • 1970-01-01
    • 2013-04-05
    • 2017-10-25
    • 2020-04-16
    • 2013-06-01
    • 1970-01-01
    • 2015-08-20
    • 2021-05-16
    相关资源
    最近更新 更多