【问题标题】:List of letter occurences Python字母出现列表 Python
【发布时间】:2021-12-27 22:01:10
【问题描述】:

我有一个编码任务,我需要创建一个程序来检查名称字典中包含字母 R、M、A、K 和 C 的次数。所以在这种情况下,我有这个字典:

dict = {"Renata", "Maciek", "Marek", "Karolina", "Marcel}

我需要创建一个循环来逐一检查字典中所有名称中的所有这些字母。完成后,它需要将结果放入一个列表中,并在程序结束时返回该列表。所以结果看起来像

R - 4 米 - 2 A - 3.(数字只是举例) K - 5 C - 6

这是我目前所拥有的:

names = {"Renata", "Marek", "Maciek", "Karolina", "Marcel"}

letter = ['R', 'M', 'A', 'K', 'C'] 

counter = 0 

for letter in names:

    print("R =", names.count("R"))
    print("M =", names.count("M"))
    print("A =", names.count("A"))
    print("K =", names.count("K"))
    print("C = ", names.count("C"))

如您所见,我对 Python 非常陌生,因此我非常感谢您的意见或帮助。请显示您对代码所做的更改。提前谢谢你

【问题讨论】:

  • 你的“字典”实际上是一个set!这很有趣,因为dictionary 在 Python 中也是一种不同的数据结构。

标签: python list dictionary computer-science


【解决方案1】:

例如,这样:

names = {"Renata", "Marek", "Maciek", "Karolina", "Marcel"}
names_concatenated = "".join(names).upper()
letters = ['R', 'M', 'A', 'K', 'C']

for letter in letters:
    print(f"Letter '{letter} occurrences count in `names`: "
          f"{names_concatenated.count(letter)}")

我们有:

Letter 'R' occurrences count in `names`: 4
Letter 'M' occurrences count in `names`: 3
Letter 'A' occurrences count in `names`: 7
Letter 'K' occurrences count in `names`: 3
Letter 'C' occurrences count in `names`: 2

【讨论】:

    【解决方案2】:

    内置collections 库中的Counter 子类对于这类事情非常方便。我会这样实现它:

    from collections import Counter
    
    names = {"Renata", "Marek", "Maciek", "Karolina", "Marcel"}
    all_letters = ''.join(names).upper()
    
    counter = Counter(all_letters)
    for l in ['R', 'M', 'A', 'K', 'C']:
        print(l, ":", counter[l])
    

    输出:

    R : 4
    M : 3
    A : 7
    K : 3
    C : 2
    

    【讨论】:

      【解决方案3】:

      这是一种方法:

      names = {"Renata", "Marek", "Maciek", "Karolina", "Marcel"}
      
      # Create a dictionary that maps each letter that we're tracking to a frequency counter.
      letter_counters = {'R': 0, 'M': 0, 'A': 0, 'K': 0, 'C': 0}
      
      # Go through the set of names, one at a time, and add the frequency of each letter that we're tracking to our counters.
      # .upper() is used to make our counting case-insensitive.
      for name in names:
          for letter in letter_counters:
              letter_counters[letter] += name.upper().count(letter)
      
      # Transform the dictionary into a list. (This could be made more concise using a list comprehension, though this is not immediately relevant to the question.)
      result = []
      for letter in letter_counters:
         result.append([letter, letter_counters[letter])
      

      【讨论】:

      • 感谢您的意见。你能澄清一下不区分大小写的含义吗?
      • 不区分大小写意味着当我们计算特定字母(例如“R”)的频率时,我们正在寻找“R”(大写)和“r”(小写)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2018-08-27
      • 1970-01-01
      • 2020-03-05
      相关资源
      最近更新 更多