试图找到元素较少的列表

4 投票
3 回答
7919 浏览
提问于 2025-04-17 12:01

我刚开始学习Python和编程。我的问题是如何在一个字典中找到元素最少的列表。简单来说,我有一个字典,大约有十个键,每个键对应一个包含很多元素的列表。

我需要遍历那个元素最少的列表。为此,我尝试定义一个函数来完成这个工作:

def minlist(*lists):
    smallest = min(len(lists))
    if len(lists) == smallest:
        return lists

但是我得到了一个错误提示:TypeError: 'int' object is not iterable。我该怎么处理这个问题呢?因为我其实并不知道有多少个键。

这里是我的字典的一个示例(如要求的那样):

{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]}

3 个回答

1

我猜你想要这样做:

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

为什么要用 lists_dict.values() 呢?默认情况下,你是遍历字典的键。但是你想要检查与这些键相关的值的长度,所以你得用到它们。

我假设你字典的结构是这样的:

# { int: list, int: list, ...}
# e.g.:
lists_dict = {1: [2,3], 2: [2,3,4,5], 3: [1], 4: [1,2,2]}

你描述的结构:

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

这样是行不通的,因为你不能用标准列表作为字典的键。

3

这里有一个更简短的写法,使用了列表推导式:

min_list=min([len(ls) for ls in dict.values()])

补充一下:你也可以使用生成器推导式(把表达式用圆括号包起来,而不是方括号),这样会更高效一些。

3

这里有一个解决方案,它使用了一个中间的元组列表,这样可以更方便地进行排序和访问:

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]]

撰写回答