【问题标题】:How do I return a dictionary of values from a list?如何从列表中返回值字典?
【发布时间】:2021-05-05 01:31:25
【问题描述】:

如何编辑注释掉的代码,使其返回包含重复数字的字典而不是返回“{}”?

listOfElems = ["a", "c", "c"]

def checkIfDuplicates_3(listOfElems):
  duplicates = {}
  for x in listOfElems:
#    duplicates = ??
    if listOfElems.count(x) > 1:
      return duplicates
  return duplicates

#test 
test = [listOfElems]

for t in test:
  output = checkIfDuplicates_3(t)
  print("The duplicate in", t, "is", output)

【问题讨论】:

  • @sagar1025 虽然它确实解决了他的整体问题,但并没有回答他的具体问题,即确定重复项所需的具体条件。
  • 你为什么选择字典而不是列表?
  • 你永远不会得到一个字典,当你将重复项分配给空字典时,你总是会得到一个列表,当你创建 for 循环时,你调用 return 语句,所以当它搜索计数并返回时运行将打破循环并返回代码的结尾,这将是空字典,所以这里不需要返回字典

标签: python list dictionary edit


【解决方案1】:

我不明白你为什么需要在这里使用字典。您没有键或值。您要做的就是返回一个在列表中重复的字母。

以下代码使用列表推导来解决您的问题。 首先我们调用这个函数,传入listOfElems。 然后我们将遍历给定的列表并检查每个元素的出现。我们可以使用count 来做到这一点。看来你也用过。如果一个字母出现多次,我们会将该字母附加到一个新列表中。

在您提供的示例中,我们最终会得到这样的结果, ['c','c']。如果c 只出现一次就好了。为了解决这个问题,我们可以使用set,这将给我们{'c'},这非常好。 为了完成这一切,我们将这个集合作为一个列表返回。

listOfElems = ["a", "c", "c"]

def checkIfDuplicates_3(listOfElems):
    dups = [x for x in listOfElems if listOfElems.count(x) > 1]
    return list(set(dups))
print("The duplicates in", listOfElems, "are", checkIfDuplicates_3(listOfElems))

【讨论】:

    【解决方案2】:

    这里有一个解决方案。

    如果列表中有多个元素listOfElems.count(x) > 1,并且我们的重复列表中不包含该元素duplicates.count(x) == 0,那么我们可以将该元素添加到重复列表中。

    listOfElems = ["a", "c", "c"]
    
    
    def checkIfDuplicates_3(listOfElems):
        duplicates = []
        for x in listOfElems:
            if listOfElems.count(x) > 1 and duplicates.count(x) == 0:
                duplicates.append(x)
        return duplicates
    
    
    # test
    test = [listOfElems]
    
    for t in test:
        output = checkIfDuplicates_3(t)
        print("The duplicate in", t, "is", output)
    

    【讨论】:

      【解决方案3】:

      使用set 和列表理解,单行函数可以做到:

      listOfElems = ["a", "c", "c","e","c","e","f"]
      
      def checkIfDuplicates_3(listOfElems): return set([x for x in listOfElems if listOfElems.count(x)>1])
      
      #test
      test = [listOfElems]
      
      for t in test:
          output = checkIfDuplicates_3(t)
          print("The duplicate in", t, "is", sorted(output))
      

      请注意,插入顺序可能不会被 set 保留。要获得有序输出,请使用sorted(如上例所示)。

      要获得一个统计出现次数的字典>1,您可以使用:

      def checkIfDuplicates_3(listOfElems):
          return {x:listOfElems.count(x) for x in set(listOfElems) if listOfElems.count(x)>1}
      

      例如返回checkIfDuplicates_3(listOfElems) 结果{'e': 2, 'c': 3}(请参阅上面的订购说明)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-31
        • 2023-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多