【问题标题】:Defining a Nested List Function for Counting Numbers of Lists and Elements in Python在 Python 中定义用于计算列表和元素数量的嵌套列表函数
【发布时间】:2022-08-17 22:28:27
【问题描述】:

我正在尝试定义一个采用嵌套列表和输出的函数:

(1) 列表中有多少个列表,

(2)每个列表的元素个数是否相同。

我有两个嵌套列表:

nl1: [[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 4, 6, 8, 10]]

nl2: [[1, 2, 3, 4, 5], [3, 4, 6, 7], [2, 4, 6, 8, 10]]

函数名称是 nlc() 嵌套列表计数

nl1 = [[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 4, 6, 8, 10]]

nl2 = [[1, 2, 3, 4, 5], [3, 4, 6, 7], [2, 4, 6, 8, 10]]

def nlc(n):

    sl = len(n)

    print(\"Number of Lists is\", sl)

    for list in n:
        r = list(map(len, n))
        if r ==list()
        print(\"Lengths Match\")
        else print(\"Lengths Not Equal; Check Lists\")

两件事情:

(P1) Python 不断返回一个错误,说 r = list(map(len, n)) 是错误的,因为它是一个字符串。

(P2) 我似乎不知道如何编写代码来检查每个嵌套列表是否具有相同数量的元素。

此外,当我测试 P1 时,它运行得很好:

nl1 = [[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 4, 6, 8, 10]]

r = list(map(len, nl1))

print(r)

所以我不确定我正在定义函数的参数发生了什么。

    标签: python list nested-lists


    【解决方案1】:

    我想您正在使用 list() 内置方法并将其用作循环中的变量,这会导致错误。您可以执行与此相同的任务

    #Function definition
    def nlc(n):
        '''It checks how many lists are in the list, and whether the number of elements in each list are the same.'''
        sl = len(n)
        print("Number of Lists is", sl)
        lengths = []
        for element in n: 
            lengths.append(len(element))          #appending length of each sublist
        if len(set(lengths)) == 1:                #checking if all elements are same in a list. It means that all lengths are equal
            print("Lengths Match")
        else:
            print("Lengths Not Equal; Check Lists")
    
    nl1 = [[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 4, 6, 8, 10]]
    nl2 = [[1, 2, 3, 4, 5], [3, 4, 6, 7], [2, 4, 6, 8, 10]]
    nlc(nl2)
    

    【讨论】:

      猜你喜欢
      • 2015-04-20
      • 2018-07-25
      • 2013-09-11
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      • 2012-08-03
      • 2020-08-17
      • 1970-01-01
      相关资源
      最近更新 更多