我被要求创建一个函数,在该函数中计算字符串中b-s的所有字母。以下是我到目前为止的情况:
def strange_count(s):
count = 0
s = s.lower()
s_count = [b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s]
while count <= len(s):
for i in range(len(s_count)):
if s_count[i] == s[count]:
count += 1
return
它返回错误,任何帮助将不胜感激
File "", line 4, in strange_count
s_count = [b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s]
NameError: name 'b' is not defined
答案 0 :(得分:2)
这一行:
s_count = [b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s]
应该是这样的:
s_count = ["b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s"]
然后你会发现你处于一个无限循环中,所以尝试重写如下:
def strange_count(s):
count = 0
s = s.lower()
s_count = ["b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s"]
for letter in s:
if letter in s_count:
count += 1
return count
print(strange_count("asfdsjfdlkwjrwoiureaoifhwabrejwer"))
答案 1 :(得分:1)
您可以使用字母按字典顺序排序的事实,而不是制作列表,这样您就可以将它们与>
和<
进行比较
def strange_count(s):
total = 0
for letter in s:
if letter >= 'b' and letter <= 's':
total += 1
return total
例如
>>> strange_count('dictionary')
7
或者更紧凑地使用生成器表达式
def strange_count(s):
return sum(1 for i in s if i >= 'b' and i <= 's')
答案 2 :(得分:1)
s_count = [b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s]
以上是不声明一个列表,其中包含与您所谈论的字母范围相对应的元素。
您真正要说的是s_count
应该是列表,其中元素的值应与名为b
,c
,{{的变量对应1}},d
,e
,f
,g
,h
,i
,j
,{{1} },k
,l
,m
,n
,o
,p
和q
。
您从 python解释器获得诊断(错误消息),因为没有声明这些变量。
如果您想创建一个字符列表,则需要将它们包含在r
或s
中(如下所示)。
'
注意:鉴于以上内容对编写和维护都非常繁琐,初始化
"
的更合适的方法是s_count = ['b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s']
- 这会产生期望的结果。
答案 3 :(得分:1)
错误表示您正在使用未定义的变量 - b
,c
等。似乎您打算使用那些字符,在这种情况下您应该环绕他们用引号:
s_count = ['b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s']
话虽如此,值得记住的是字符是序数的,所以你可以使用<=
和>=
运算符。另外,当你可以使用sum
和列表理解时,恕我直言,为此定义一个函数似乎有点过分:
mystring = 'some string'
strange_count = sum(1 for c in s if c >= 'b' and c <= 's')
答案 4 :(得分:0)
在您的情况下,您可以Mureinik's answer查看每个字符是否为&gt; =“b”和&lt; =“s”,另一种指定某些字符的有效方法是使用一组你要检查的字符,并总结s中字符集的多少次:
def strange_count(s):
s = s.lower()
s_count = {"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s"}
return sum(ch in s_count for ch in s)
就你的错误而言,你需要使用双引号或单引号实际创建字符串:
["b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s"]
使用b,
c ...
python将查找使用名称a, b, c....
定义的变量,因此除非您实际在某处定义了这些变量,否则您将获得NameError
。
如果您使用&lt; =那么您可以使用"b" <= ch <= "s"
的简化链式表达式sum
:
def strange_count(s):
return sum("b" <= ch <= "s" for ch in s)
答案 5 :(得分:0)
如果您没有处理很长的字符串,或者您没有被要求考虑计算成本,您可以使用以下内容:
input = "Hello world"
input = input.lower()
list_chars = ['b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s']
counts = {}
for c in list_chars:
counts[c] = input.count(c)
print counts