【问题标题】:Trying to find the list with fewer elements试图找到元素较少的列表
【发布时间】:2012-02-23 00:46:15
【问题描述】:

我对 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]}

【问题讨论】:

  • 列表不能是键!!你能说清楚一点吗? (请提供更多代码)
  • 您发布的代码会给您带来高于一切的语法错误。
  • 你应该澄清你的问题。提供字典样本将是一个很好的开始。

标签: python list function dictionary


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • ..或者你也可以省略方括号
    【解决方案3】:

    我想你想这样做:

    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, ...}
    

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

    【讨论】:

    • 它似乎有效,但由于某种奇怪的原因,它返回具有“最大”元素数量的列表,而使用 max() 它返回具有较少元素的列表。
    • 哦,我刚刚意识到这是因为,列表在 min 函数中的比较方式。我调整了上面的代码以正常工作。结果取决于列表的长度。不是最短的,但有效:)。您应该使用这个或 Bogdan 的那个
    猜你喜欢
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2015-12-16
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多