【发布时间】: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