Python 正在尝试查找元素较少的列表

Python 正在尝试查找元素较少的列表,python,list,function,dictionary,Python,List,Function,Dictionary,一般来说,我对Python和编程相当陌生。我的问题是通过哪些操作可以找到字典中元素最少的列表。我有一本大约有十个键的字典,每个键都是一个包含很多元素的列表。 我需要用最少的元素遍历列表。为了找到它,我尝试定义一个函数来完成这项工作: def minlist(*列表): 最小值=最小值(长度(列表)) 如果len(列表)=最小值: 退货清单 但响应是TypeError:“int”对象不可编辑。考虑到原则上我不知道钥匙的数量,我怎么能做到这一点? 这是我的字典样本(根据需要) {97:[10079

一般来说,我对Python和编程相当陌生。我的问题是通过哪些操作可以找到字典中元素最少的列表。我有一本大约有十个键的字典,每个键都是一个包含很多元素的列表。 我需要用最少的元素遍历列表。为了找到它,我尝试定义一个函数来完成这项工作:

def minlist(*列表):
最小值=最小值(长度(列表))
如果len(列表)=最小值:
退货清单
但响应是
TypeError:“int”对象不可编辑。考虑到原则上我不知道钥匙的数量,我怎么能做到这一点?
这是我的字典样本(根据需要)

{97:[1007928679693166,
1007928798219684,
1007928814680980,
1007928891466688,
1007928897515544,
1007928997487142],
98: [1007928837651593, 1007928889730933],
99: [1007928797944536,
1007928805518205,
1007928870847877,
1007929012532919,
1007929030905896,
1007929097107140],
688: [1007928628309796,
1007928724910684,
1007928808626541,
1007928866265101,
1007928908312998,
1007928982161920,
1007929013746703,
1007929055652413],
734: [1007928687611100,
1007928923969018,
1007928933749030,
1007928942892766,
1007929021773704],
1764: [1007928765771998, 1007928917743164],
1765: [1007928894040229, 1007929021413611],
1773: [1007929003959617]}

我想你应该这样做:

def minlist(lists_dict):
  min_list = None
  for list in lists_dict.values():
    if min_list == None: 
      min_list = list
    else:
      if len(list) < len(min_list):
        min_list = list

    return min_list
您描述的结构:

# { list: list, list: list, ...}

不起作用,您不能使用标准列表作为字典的键。

这里有一个解决方案,使用元组的中间列表以方便排序/访问:

input_dict = {1: [1,2,3,4], 2: [2,3,4], 3:[1,2,3]}
#Get key/length(list) type tuples
helper = [(key, len(input_dict[key])) for key in input_dict.keys()]
#Sort list by the second element of the tuple(the length of the list) 
helper.sort(key=lambda x: x[1])

#Now the first position hold the key to the shortest list from the dicitonary and the length
print input_dict[helper[0][0]]

下面是一个使用列表理解的更短版本:

min\u list=min([len(ls)表示目录值()中的ls])


编辑:这也可以使用生成器理解(将表达式用圆括号括起来,而不是用方括号括起来)来获得更高效的版本

列表不能是键!!你能说清楚点吗?(请提供更多代码)您发布的代码将首先为您提供语法错误。您应该澄清您的问题。提供一个字典示例将是一个很好的开始。它似乎可以工作,但出于某种奇怪的原因,它返回的列表包含“最大”数量的元素,而使用max()它返回的列表包含较少的元素。哦,我刚刚认识到这一点,因为在min函数中列表是如何比较的。我调整了上面的代码以正确工作。结果取决于列表的长度。不是最短的,但有效:)。你应该用这个或者Bogdan的那个,或者你也可以省略方括号
input_dict = {1: [1,2,3,4], 2: [2,3,4], 3:[1,2,3]}
#Get key/length(list) type tuples
helper = [(key, len(input_dict[key])) for key in input_dict.keys()]
#Sort list by the second element of the tuple(the length of the list) 
helper.sort(key=lambda x: x[1])

#Now the first position hold the key to the shortest list from the dicitonary and the length
print input_dict[helper[0][0]]