简体   繁体   English

计算一个单词中不同字符的数量

[英]Counting number of different characters in a word

I am trying to think of a program to count the number of different characters in a word in Python.我正在想一个程序来计算 Python 中一个单词中不同字符的数量。

For example:例如:

  • Given the input:鉴于输入:

     ('Banana')
  • Expected output:预期输出:

     3

How can I use a while or for loop to do this?如何使用whilefor循环来执行此操作?

Thanks谢谢

A loop for this is not required.不需要为此循环。 You can find the unique characters in a string using set您可以使用set查找字符串中的唯一字符

len(set('Banana'))

This will output 3 .这将输出3 If you want to see what characters are unique, remove the len wrapper:如果要查看哪些字符是唯一的,请删除len包装器:

set('Banana')

Outputs:输出:

set(['a', 'B', 'n'])

Note: B and b are unique.注: Bb是唯一的。 If you have a word like Baby you'll get this:如果你有一个像Baby这样的词,你会得到这个:

set(['a', 'y', 'B', 'b'])

To prevent this, convert your string to either all caps or all lower case:为了防止这种情况,请将您的字符串转换为全部大写或全部小写:

set('Baby'.lower())

Outputs:输出:

set(['a', 'y', 'b'])
>>> len(set('Banana'))
3

Note: For future readers, this solution is only accepted because the OP was restricted to using loops.注意:对于未来的读者,仅接受此解决方案,因为 OP 仅限于使用循环。 @Andy's solution provides a much better alternative using Python'sset() function. @Andy 的解决方案使用 Python 的set()函数提供了更好的替代方案。

Using a for loop:使用 for 循环:

word='Banana'

L=[]                           #create an empty list
for letter in word:
    if letter not in L:
        L.append(letter)       #append unique chars to list

print len(L)                   #count the chars in list

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM