[英]How value a List without IN operator
I have this Question: Write a function is_member() that takes a value (ie a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. 我有一个问题:编写一个函数is_member(),该函数接受一个值(即数字,字符串等)x和值列表a,如果x是a的成员,则返回True,否则返回False。 (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.) my code: (请注意,这正是in运算符的功能,但是为了便于练习,您应该假装Python没有该运算符。)我的代码:
def is_member(a):
a = raw_input("Give a Number: ")
b = ['hallo', '120', 'me']
for i in a:
if a[i] == b:
return True
else:
return False
print is_member('a')
Mit IDLE console , I come : TypeError: string indices must be integers, not str .Where is the problem ?? Mit IDLE控制台,我来了:TypeError:字符串索引必须是整数,而不是str。 . 。 Very Thanks for yours help! 非常感谢您的帮助!
Your a
is a str
(string), next you use a for
loop to iterate over the characters of that string? 您的a
是一个str
(字符串),接下来您使用for
循环遍历该字符串的字符吗?
You probably want to do it the opposite way. 您可能想要相反的方法。 Either: 要么:
for i in b:
if a == i:
return True
return False
Or: 要么:
for i in range(len(b)):
if a == b[i]:
return True
return False
Note that you can't return False
in the else
case: it is not because the first check fails, the remaining checks cannot eventually yield an element that is equivalent. 请注意,在else
情况下,您不能 return False
:不是因为第一个检查失败,其余的检查最终不能产生等效的元素。 You thus have to loop through the entire collection before you know for sure the element is not in the list*. 因此,您必须先遍历整个集合,然后才能确定该元素不在列表中*。
First of all, if you want to use raw_input
then you don't need the parameter of is_member
because a
always becomes the return value of raw_input
. 首先,如果要使用raw_input
则不需要is_member
的参数,因为a
始终成为raw_input
的返回值。
Also a
is a string
, not list
, so i
is string
. 另外a
是string
,而不是list
,所以i
是string
。 Example: 例:
>>> for i in 'abc':
... print(i)
...
a
b
c
is_member
should be: is_member
应该是:
def is_member():
a = raw_input("Give a Number: ")
b = ['hallo', '120', 'me']
return a in b
print is_member()
or 要么
def is_member(a):
b = ['hallo', '120', 'me']
return a in b
print is_member('a')
Your problem is that the for loop sets i
to hold the values of a
in turn, and so when you reference a[i]
, it tries to find a['hallo']
, which it clearly cannot. 您的问题是,for循环将i
设置为依次包含a
的值,因此,当您引用a[i]
,它将尝试查找a['hallo']
,但显然无法这样做。 You simply need to replace a[i]
with i
, and then it should work perfectly. 你只需要更换a[i]
与i
,然后它应该很好地工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.