简体   繁体   English

如何让我的 output 返回 '*' 每个字母在字符串中出现的次数?

[英]How can I make my output return '*' for the number of times each letter appears in a string?

So despite asking for help previously, a lot of the responses were extremely helpful, but me, as a beginner, I am struggling to see how they are being used..因此,尽管之前寻求帮助,但很多回复都非常有帮助,但我,作为一个初学者,我很难看到它们是如何被使用的。

Nevertheless, I had a go myself again and so I'm trying to create a program that will return '*' times the number of times each letter appears in a string, and here is what I have so far...尽管如此,我自己又拥有了一个 go ,所以我正在尝试创建一个程序,该程序将返回 '*' 乘以每个字母在字符串中出现的次数,这就是我到目前为止所拥有的......

def numberofletters(filename: str):
    g = list(filename)
    f = []
    for x in set(g):
        f.append(x)
    return f
def numberofwords(filename):
    r = []
    for x in filename:
        r.append([numberofletters(filename),filename.count(x)*('*')])
    return r
print(numberofwords("How was your day"))

However, it doesn't work at all since this is the output I'm getting..但是,它根本不起作用,因为这是我得到的 output..

[[[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 1], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 2], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 2], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 3], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 2], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 2], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 1], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 3], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 2], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 2], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 1], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 1], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 3], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 1], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 2], [[' ', 'u', 'w', 'H', 'y', 'd', 'r', 'a', 'o', 's'], 2]]

but the answer that my code is supposed to print out is something like this但是我的代码应该打印出来的答案是这样的

Note that the output below is a sample of what the output should look like btw请注意,下面的 output 是 output 应该看起来像 btw 的示例

e ++++++++++++++++++++++++
t ++++++++++++++++++
s +++++++++++++++++
i ++++++++++++++++
a +++++++++++++++
m ++++++++++++
r ++++++++++++
u ++++++++++++
l +++++++++
n +++++++++
o +++++++++
c +++++++
d +++++++
p +++++++
b +++++
g ++
h ++
j +
v +

Please try to use as less built in functions as possible, and also please do not use import and key = lamda or stuff like that because I'm kinda new and I don't really know how to use it请尝试使用尽可能少的内置函数,也请不要使用 import 和 key = lamda 或类似的东西,因为我有点新,我真的不知道如何使用它

It would really help if you just modified my code btw instead of creating a new one ig, Thank you!如果您只是修改了我的代码而不是创建一个新的 ig,那将真的很有帮助,谢谢!

Your numberofletters function您的字母数numberofletters

  • does not return the number of letters, but the unique letters of a given word, so you should change your implementation to do that.不返回字母的数量,而是给定单词的唯一字母,所以你应该改变你的实现来做到这一点。

  • does not receive a file name in your example, but a phrase or a string, so you should rename the filename parameter to something more generic.在您的示例中没有收到文件名,而是一个短语或一个字符串,因此您应该将filename参数重命名为更通用的名称。

The following implementation uses a dictionary:以下实现使用字典:

def letter_count(phrase: str) -> dict:
    # Creates a dictionary to store each letter to its count
    counter = {}

    # Iterate over each letter inside your phrase
    for letter in phrase:
        # If this letter is present in the counter,
        # return its count. Otherwise, return zero
        letter_count = counter.get(letter, 0)
        
        # Put this letter into the counter incrementing its value
        counter[letter] = letter_count + 1
        
    return counter

Now, just sort and print it accordingly:现在,只需对它进行相应的排序和打印:

# Call the function to calculate its value
counter = letter_count("How was your day")

# Sort the dictionary based on the count of each letter in the descending order
sorted_counter = sorted(counter.items(), key=lambda x: x[1], reverse=True)

# Iterate over each letter and count inside the sorted counter
for letter, count in sorted_counter:
    # Print the letter and the `+` character repeated `count` times
    print(letter, '+' * count)

Since you don't know how to use key=lambda... , I suggest you to take a look at key functions .由于您不知道如何使用key=lambda... ,我建议您看一下key functions

This is as simple and as explicit as I can make it:这是尽可能简单和明确的:

def letter_count(filename: str):
    chars = list(filename.lower()) # ['h', 'o', 'w', ' ', 'w', 'a', 's', ' ', 'y', 'o', 'u', 'r', ' ', 'd', 'a', 'y']
    chars_unique = set(chars) # {'s', 'h', 'u', 'w', 'o', 'd', 'a', 'r', ' ', 'y'}
    chars_unique.remove(' ') # {'s', 'h', 'u', 'w', 'o', 'd', 'a', 'r', 'y'}
    result = []
    for x in chars_unique:
        # creates a list e.g. ['w', '**'] and adds it to the result list
        result.append([x, chars.count(x)*('*')])
    return result

l_count = letter_count("How was your day") # [['s', '*'], ['h', '*'], ['u', '*'], ['w', '**'], ['o', '**'], ['d', '*'], ['a', '**'], ['r', '*'], [' ', '***'], ['y', '**']]

for c in l_count:
    print(c[0], c[1])

Which returns:返回:

a **
r *
y **
h *
s *
u *
o **
d *
w **

If you want the bars to be in descending order, then you have to order the data before printing it:如果您希望条形按降序排列,则必须在打印之前对数据进行排序:

# MODIFIED TO ORDER THE BARS
def letter_count(filename: str):
    chars = list(filename.lower()) # ['h', 'o', 'w', ' ', 'w', 'a', 's', ' ', 'y', 'o', 'u', 'r', ' ', 'd', 'a', 'y']
    chars_unique = set(chars) # {'s', 'h', 'u', 'w', 'o', 'd', 'a', 'r', ' ', 'y'}
    chars_unique.remove(' ') # {'s', 'h', 'u', 'w', 'o', 'd', 'a', 'r', 'y'}
    result = []
    for x in chars_unique:
        # creates a list e.g. ['w', '**'] and adds it to the result list
        result.append([x, chars.count(x)*('*')])
    result.sort(key=lambda x: len(x[1]), reverse=True)
    return result

Lets break this modification down:让我们分解一下这个修改:

.sort() Sorts a Python list inplace (modifies result directly) .sort()就地对 Python 列表进行排序(直接修改结果)

lambda x: len(x[1]) Anonymous function, gets the length of the first index of the input Exactly the same as the following, except we can give the following a name f lambda x: len(x[1])匿名 function,获取输入的第一个索引的长度 和下面完全一样,除了我们可以给下面一个名字f

def f(x):
    return len(x[1])

key=lambda x: len(x[1]) Defines what we want to sort on, the number of stars in this case which is the length first index of the inner lists key=lambda x: len(x[1])定义我们想要排序的对象,在这种情况下是星的数量,它是内部列表的长度第一个索引

result.sort(key=lambda x: x[1], reverse=True) makes it DESCENDING order result.sort(key=lambda x: x[1], reverse=True)使其降序

Which gives:这使:

y **
a **
o **
w **
r *
h *
d *
s *
u *

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据字母在列表中出现的次数将我的输出打印为“+”? - How can I make my output be printed as '+' for the number of times a letter appears in a list? 返回一个字母在一个字符串中出现多少次 - Return how many times each letter of the alphabet appears in a string 如果字符串中的字符连续出现 3 次,如何使 output 返回 False? - How can I make the output return False if a character in the string appears three times in a row? 如何计算每个字母在列表中的字符串中出现的次数 - How can I tally the number of times each letter occurred in a string in a list 计算每个字母在字符串中出现的次数 - Counting how many times each letter appears in the string 你如何让 python 使用字符串字母的顺序作为字典的一部分,其中每个唯一字母出现的次数的值 - How do you make python use the order of the letters of a string as part of a dictionary with values for the amount of times each unique letter appears 带有字典的函数,该函数以字符串作为输入并计算每个字母出现的次数 - Function with dictionary that takes a string as input and counts the number of times each letter appears wont print 如何返回具有特定要求的字符串在列表中出现的次数? - How to return the number of times a string with specific requirements appears in a list? 如何计算每个单词在 txt 文件中出现的次数? - How can I count the number of times each word appears in a txt file? 如何打印字符串中每个字母出现的次数? - How can i print number of times each alphabet occurs in the string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM