📜  Python – 值列表长度

📅  最后修改于: 2022-05-13 01:54:51.312000             🧑  作者: Mango

Python – 值列表长度

很多时候,在处理任何语言的容器时,我们都会遇到不同形式的元组列表,元组本身有时可能比本机数据类型更多,并且可以将列表作为它们的属性。本文将列表的长度作为元组属性进行讨论。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表理解 + len()
这个特殊问题可以使用列表推导结合 len函数来解决,其中我们使用 len函数将列表的 len 查找为元组属性,并使用列表推导遍历列表。

# Python3 code to demonstrate
# Value list lengths
# using list comprehension + len()
  
# initializing list
test_list = [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension + len()
# Value list lengths
res = [(key, len(lst)) for key, lst in test_list]
  
# print result
print("The list tuple attribute length is : " + str(res))
输出 :
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
The list tuple attribute length is : [('key1', 3), ('key2', 3), ('key3', 2)]

方法 #2:使用 map + lambda + len()
上述问题也可以使用 map函数将逻辑扩展到整个列表来解决,len函数可以执行与上述方法类似的任务。

# Python3 code to demonstrate
# Value list lengths
# using map() + lambda + len()
  
# initializing list
test_list = [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
  
# printing original list
print("The original list : " + str(test_list))
  
# using map() + lambda + len()
# Value list lengths
res = list(map(lambda x: (x[0], len(x[1])), test_list))
  
# print result
print("The list tuple attribute length is : " + str(res))
输出 :
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
The list tuple attribute length is : [('key1', 3), ('key2', 3), ('key3', 2)]