【问题标题】:Grouping Transactions by Items' Names按项目名称对交易进行分组
【发布时间】:2022-01-15 14:36:12
【问题描述】:

使用 Python3

对于给定的交易数组,按项目名称对所有交易进行分组。返回一个字符串数组,其中每个字符串包含项目名称,后跟一个空格和关联交易的数量。

注意:对数组按交易计数降序排序,然后对匹配交易计数的项目按项目名称的字母顺序升序。

示例

transactions = ['notebook', 'notebook', 'mouse', 'keyboard', 'mouse']

有两个项目,每个项目有 2 个事务:“笔记本”和“鼠标”。按字母顺序,它们是“鼠标”、“笔记本”。 有一项具有 1 笔交易:“键盘”。 按要求排序的返回数组为['mouse 2', 'notebook 2', 'keyboard 1']

我有什么

def get_trans(lst):
    ans = {}

   for i in lst:
      ans[i] = ans.get(i, 0) + 1
   return ans

dictionary = get_trans(transactions)

print(dictionary)

{'notebook' : 2, 'mouse' : 2, 'keyboard' : 1}

data = list(dictionary.items())
an_array = np.array(data)
print(an_array)

当前输出:'notebook' 出现在 'mouse' 之前,字数/计数分开字符串

[['notebook' '2']
 ['mouse' '2']
 ['keyboard' '1']]

期望的输出:'notebook' 按字母顺序排列在'mouse'之后,字数/计数是一个字符串

['mouse 2', 'notebook 2', 'keyboard 1']

【问题讨论】:

  • 这似乎是一个家庭作业问题。让我们知道您已经尝试过什么并提出更具体的问题。
  • 你想知道我尝试了什么。其他人编辑了我尝试过的内容。我们绕着绕着走
  • 然后把问题改得更具体一些,你在哪个部分有问题?这个问题要求多方面的东西。不要仅列出您遇到问题的所有要求。如果您愿意,可以创建一个新问题。
  • @VikashBalasubramanian 见上文编辑
  • 一个简单的错误/错别字 - 你想要 ans.get(i, 0) + 1 而不是 ans.get(0, 1) + 1

标签: python string list grouping counter


【解决方案1】:

Manlai A 提供了正确答案。我已将其转换为函数:

def get_trans(lst):
    ans = {}
    for i in lst:
        ans[i] = ans.get(i, 0) + 1
    return ans

# A function using get_trans() function with Manlai A's answer
def grouping(lst):
    out = sorted(get_trans(lst).items(), key=lambda x:(-x[1],x[0]))
    out = [' '.join([t[0],str(t[1])]) for t in out]
    return out

# Passing transactions list into the new function

grouping(transactions)

输出:

['mouse 2', 'notebook 2', 'keyboard 1']

【讨论】:

    【解决方案2】:

    您的函数几乎是正确的,只是您需要先将密钥传递给get 方法,然后再传递一个默认值。然后您可以使用sorted 函数对dictionary 中的键值对元组进行排序,计数按降序排列,项目名称按升序排列:

    def get_trans(lst):
        ans = {}
        for i in lst:
            ans[i] = ans.get(i, 0) + 1
        return ans
    
    out = [' '.join([t[0],str(t[1])]) for t in sorted(get_trans(transactions).items(), key=lambda x:(-x[1],x[0]))]
    

    输出:

    ['mouse 2', 'notebook 2', 'keyboard 1']
    

    【讨论】:

    • 感谢指正。您的答案输出似乎是三个元组。期望的答案是三个字符串 ['mouse 2', 'notebook 2', 'keyboard 1'] @Manlai A
    • @WilhelmGleiss 看到编辑。
    • 惊人的工作! @Manlai A. 你会编辑你的输出以反映正确的输出吗
    猜你喜欢
    • 1970-01-01
    • 2012-05-23
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多