【问题标题】:List in a list recognition in pythonpython中的列表识别中的列表
【发布时间】:2014-07-30 17:03:59
【问题描述】:

我编写了这个简单的代码来实现列表中的成员是否是列表本身,如果是则打印成员。我很想知道这是否是正确的接近方式:

listt = ['spam!', 1, ['B', 'R', 'P'], [1 , 2, 3]]
leng= range(len(listt))

def listPrint(listt, leng):
    for i in leng:

        print "List member",i,":"
        list1 = listt[i]
        print listt[i]


        if isinstance(listt[i], list):
            leng2 = range(len(listt[i]))
            print 'and the members are:'
            for e in leng2:
                print list1[e], '\n'

        else:
            print '\n'

listPrint(listt,leng)

【问题讨论】:

  • 为什么要使用range()?只需使用for elem in listt,直接使用elem即可。
  • 嗯,你测试过吗?它有效吗?如果是这样,这可能更适合codereview.stackexchange.comHere 是另一个问题的替代实现。
  • if all(isinstance(x, list) for x in list1) 可能会更好。
  • 是的,我已经测试过了。
  • Martjin Pieters,如果我不使用范围,那么当我在函数内部说: print listt[i] 它说我应该是整数!

标签: python list


【解决方案1】:

这是一个更简洁的版本,带有一些内嵌的 cmets:

def list_print(lst): # PEP-8 function name
    """Print the list, including sub-lists, item by item.""" # docstring
    for index, item in enumerate(lst): # use enumerate to get item and index
        print "List member {0}: ".format(index) # use str.format to create output
        print repr(item) # repr gives e.g. quotes around strings
        if isinstance(item, list):
            print "and the members are:"
            for subitem in item: # iterate directly over list
                print repr(subitem)
        print "" # blank line between items

一些注意事项:

  • Python 有 an official style guide,您应该阅读并至少考虑关注它;
  • 包括文档,尤其是当您的函数做了一些令人惊讶的事情时(例如期望 leng 是一个范围,而不仅仅是整数长度);
  • Python 包含大量用于迭代事物的功能,for i in range(len(...)) 很少是正确答案:
    • enumeratezip 和普通的 for x in y 更易于阅读和使用;
    • 至少,您应该将range(len(listt)) 移到函数内部,不要传递可以从同一个对象中获取的两条信息;和
  • 使用str.format 比将多个参数传递给print 更简洁,更符合Python 风格。

使用中:

>>> list_print(['spam!', 1, ['B', 'R', 'P'], [1 , 2, 3]])
List member 0: 
'spam!'

List member 1: 
1

List member 2: 
['B', 'R', 'P']
and the members are:
'B'
'R'
'P'

List member 3: 
[1, 2, 3]
and the members are:
1
2
3

【讨论】:

  • 我明白你的意思。 “Pythonic”是指更“面向对象”吗?我想我需要时间来消化这一切:)
  • @Sasan 参见例如What does Pythonic mean?
  • 我回顾了你使用的内置函数。确实很有用!但是由于我对编码很陌生,我宁愿尝试在不使用函数的情况下编写代码,然后在我理解逻辑之后,我使用函数来简化代码!你同意吗?
  • @Sasan 由你决定,但丰富的标准库是 python 的主要优势,你应该掌握它
【解决方案2】:

Python 的 for 循环实际上以与其他语言中的 foreach 循环相同的方式遍历项目。这与 Python 内置的 type() 函数配合使用,可以真正简化流程。

def listPrint(listt):
    i=0  #for counting the members of the list
    for elem in listt:  #Now you can use each element directly
        print "List member",i,":"
        print elem
        if type(elem) is list:
            print " and the members are: "
            for thing in elem:
                print thing
        print '\n'
        i+=1

编辑:

这是使用isinstance() 的版本,如果您愿意使用的话。我总是使用type() 来处理这类事情,所以这是我的第一个想法,但我想我应该首先整合你使用的内容。

def listPrint(listt):
    i=0  #for counting the members of the list
    for elem in listt:  #Now you can use each element directly
        print "List member",i,":"
        print elem
        if isinstance(elem, list):
            print " and the members are: "
            for thing in elem:
                print thing
        print '\n'
        i+=1

【讨论】:

  • isinstance 很好 - 比 type 更好,因为它处理继承 - 你应该真正测试平等 (==) 而不是身份 (is)。
  • 在 type() 的情况下真的有什么不同吗?它工作得很好。
  • 对于我的两点 - 您当前的代码可以工作,但可能会更好。
  • 抱歉,“工作”这个词用错了。我的意思是它实际上会影响代码的性能吗?在这种基本情况下,isinstance() 和 type() 应该可以互换,并且在这种情况下比较身份与相等性并不重要,因为无论如何它们都评估为 True。在这种情况下,是什么让身份比平等更糟糕?
  • 在这种情况下不是。 type 可以在这里工作,但是为什么在 OP 已经有了更好的东西时使用它? Apparently list 等是单例,所以 is 是正确的 - 对此感到抱歉。跨度>
最近更新 更多