为什么没有为下面的.py文件打印第一个字符数?

时间:2018-01-10 19:55:58

标签: python python-3.x python-2.7

获取每个独特字符的出现次数。它仍然没有任何错误,但没有在字符串“ str ”中出现的第一个字符( s )上打印计数。

import string
str="sdffDFREWFSDFWSSSSDWEWSWQDDddcdcdd"
j=0
exists=[]

#Iterated throughout the sting object

for i in range(len(str)):

   for j in range(i):
      if str[i]==str[j]:
         continue
      elif str[i] not in exists:
         print (" %c exists %d times" %(str[i],str.count(str[i])))
         exists.append(str[i])

3 个答案:

答案 0 :(得分:2)

核心问题是您在没有必要的情况下使用嵌套循环,并且完全跳过第二个循环的第一次运行,因为for j in range(i):如果i为零则不进行迭代。对您的方法进行最简单的修正就像是

str ="sdffDFREWFSDFWSSSSDWEWSWQDDddcdcdd"

exists=[]

for i in range(len(str)):
    if str[i] not in exists:
        print (" %c exists %d times" %(str[i],str.count(str[i])))
        exists.append(str[i])

更像pythonic的版本就像是

myStr = "sdffDFREWFSDFWSSSSDWEWSWQDDddcdcdd"
seen = set()
for letter in myStr:
    if letter not in seen:
        seen.add(letter)
        print(" %c exists %d times"%(letter, myStr.count(letter)))

答案 1 :(得分:0)

我只是逐字逐句地遍历字符串并用dict计算字符:

str="sdffDFREWFSDFWSSSSDWEWSWQDDddcdcdd"
character_occurence = dict()
for char in str:
  character_occurence[char] = character_occurence.get(char,0) + 1

现在character_occurence包含字符串中每个字符的出现次数。致电character_occurence["s"]将返回字符串中s个字符的数量。

答案 2 :(得分:0)

编辑 Better Solution Here

str="sdffDFREWFSDFWSSSSDWEWSWQDDddcdcdd"
exists=[]

   #Iterated throughout the sting object

for i in range(len(str)):
    for j in range(len(str)):
        if str[i]==str[j]:
            continue
        elif str[i] not in exists:
            print (" %c exists %d times" %(str[i],str.count(str[i])))
            exists.append(str[i])

这是我的3.x版python中的一个有效解决方案。不需要初始j值,我转换第二个范围检查也使用字符串对象的长度。