函数,该函数需要Python中的元素的3d列表和计数



您对我如何创建一个函数有什么想法吗?该函数需要一个3D列表,并计算元素和唯一元素。

例如以下列表:

list_3d = [[[1,5],[7,3],[1,5,8]]]

元素的数量应为7,唯一元素的数量为-5。

我知道你是个初学者。

因此,最佳实践是从头开始编码。

答案是,请好好学习:

from numpy import unique

def main(list_3d):
list_len = 0
list_uniq = []
for i in list_3d:
for j in i:
for m in j:
list_len += 1
if m not in list_uniq:
list_uniq.append(m)
return list_len, list_uniq

if __name__ == '__main__':
input_list_3d = [[[1, 5], [7, 3], [1, 5, 8]]]
input_list_3d_len = unique(input_list_3d)
assert(input_list_3d_len.size == 3)
list_length, list_unique = main(input_list_3d)
print("List length: {}".format(list_length))
print("List unique count: {}".format(len(list_unique)))

输出为:

List length: 7
List unique count: 5

作为练习,您可以使用built-in方法实现相同的操作

您可以使用itertools.chain.from_iterable来获取长度,然后使用其set来获取唯一元素的长度。

from itertools import chain
list_3d = [[[1,5],[7,3],[1,5,8]]]
flattened = list(chain.from_iterable(*list_3d))
length = len(flattened)
unique = len(set(flattened))
print(length, unique)

结果:

7, 5

创建一个期望3D列表的函数

  • 如何检查函数是否期望三维矩阵

这里有一个函数,它将检查嵌套列表是否正好嵌套三层(不使用任何外部库(。不确定您的需求,但根据您的示例,它只考虑列表中的列表。

def chk(a):
w = isinstance(a,list)
if w:
x = all(isinstance(obj,list) for obj in a)
else:
return False
if x:
y = all(isinstance(obj,list) for item in a for obj in item)
else:
return False
if y:
z = any(isinstance(obj,list) for item in a for thing in item for obj in thing)
else:
return False
return not z

如果这太过冗长,可以对其进行重构:

def chk(a):
if not isinstance(a,list):
return False
if not all(isinstance(obj,list) for obj in a):
return False
if not all(isinstance(obj,list) for item in a for obj in item):
return False
return not any(isinstance(obj,list) for item in a for thing in item for obj in thing)

In [12]: chk([[1],[2]])    # 2-d
Out[12]: False
In [13]: chk([[[1]],[[2]]])    # 3-d
Out[13]: True
In [14]: chk([[[1]],[[2],3]])    # not quite 3-d
Out[14]: False
In [15]: chk([[[[1]]],[[[2]]]])    # 4-d
Out[15]: False

如果你想要的话,如果有人试图从你身边偷东西,你的函数可以引发ValueError。

In [18]: if not chk([1,2]):
...:     raise ValueError('Only 3-d arrays please')
...: 
Traceback (most recent call last):
File "<ipython-input-18-53fc36f743cb>", line 2, in <module>
raise ValueError('Only 3-d arrays please')
ValueError: Only 3-d arrays please

相关内容

最新更新