在Python 2.7中获取列表的长度作为字典中的值 [英] Obtaining length of list as a value in dictionary in Python 2.7
问题描述
我有两个列表和字典,如下所示:
I have two lists and dictionary as follows:
>>> var1=[1,2,3,4]
>>> var2=[5,6,7]
>>> dict={1:var1,2:var2}
我想从我的字典中找到可变元素的大小,即键值的长度.查找 help('dict')
后,我只能找到返回键数的函数,即 dict .__ len __()
.我尝试了 Java 方法(希望它可以工作)即 len(dict.items()[0])
但它评估为 2
.
I want to find the size of the mutable element from my dictionary i.e. the length of the value for a key.
After looking up the help('dict')
, I could only find the function to return number of keys i.e. dict.__len__()
.
I tried the Java method(hoping that it could work) i.e. len(dict.items()[0])
but it evaluated to 2
.
我打算找到这个:
第一个键的值的长度: 4
第二个键的值的长度: 3
当列表是词典的一部分时,而不是单独的列表(如果它们的长度为 len(list)
).
when the lists are a part of the dictionary and not as individual lists in case their length is len(list)
.
任何建议都会有很大帮助.
Any suggestions will be of great help.
推荐答案
dict.items()
是一个包含字典所有键/值元组的列表,例如:
dict.items()
is a list containing all key/value-tuples of the dictionary, e.g.:
[(1, [1,2,3,4]), (2, [5,6,7])]
因此,如果您编写 len(dict.items()[0])
,那么您会要求该项目列表的第一个元组的长度.由于字典的元组始终为2元组(对),因此长度为 2
.如果您想要给定键的值的长度,请输入:
So if you write len(dict.items()[0])
, then you ask for the length of the first tuple of that items-list. Since the tuples of dictionaries are always 2-tuples (pairs), you get the length 2
. If you want the length of a value for a given key, then write:
len(dict[key])
Aso:尽量不要使用标准类型的名称(例如 str
, dict
, set
等)作为变量名称.Python不会抱怨,但是它会隐藏类型名称,并可能导致意外的行为.
Aso: Try not to use the names of standard types (like str
, dict
, set
etc.) as variable names. Python does not complain, but it hides the type names and may result in unexpected behaviour.
这篇关于在Python 2.7中获取列表的长度作为字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!