[英]Python: Matching a string to list item?
cords = []
for y in range(10):
for x in range(10):
cords.append((x, y))
print cords
print cords[11]
user_x=raw_input("X: ")
user_y=raw_input("Y: ")
xy = "("+user_x+", "+user_y+")"
print xy
if xy in cords:
print "Found Match"
My question is, why doesn't it print "Found Match", when given 1 and 1 or any other match? 我的问题是,给定1和1或任何其他匹配项时,为什么不打印“ Found Match”?
因为字符串永远不会等于元组。
xy = (int(user_x), int(user_y))
I haven't run the code, but it looks like: 我没有运行代码,但看起来像:
xy = "("+user_x+", "+user_y+")"
xy =“(” + user_x +“,” + user_y +“)”
is a string like so: 是这样的字符串:
"(3, 2)"
“(3,2)”
Your list is a list of tuples. 您的列表是元组列表。
Because "("+user_x+", "+user_y+")"
results in a string, and your cords
list contains tuples of integers. 因为
"("+user_x+", "+user_y+")"
生成字符串,所以您的cords
列表包含整数元组。
Instead of constructing a string you should just be putting the x and y values in a tuple like so: 不必构造一个字符串,您应该将x和y值放在一个元组中,如下所示:
xy = (user_x, user_y)
Or even just: 甚至只是:
if (user_x, user_y) in cords:
print "Found Match"
Wow. 哇。 Well, there are at least two issues here that I can see.
好吧,我至少可以看到两个问题。
Firstly, the co-ordinates are integers when they're created. 首先,坐标在创建时是整数。
raw_input
returns a string. raw_input
返回一个字符串。
Secondly, xy
is a string, and the co-ordinates are tuples. 其次,
xy
是一个字符串,坐标是元组。
>>> type(xy)
<type 'str'>
>>> type(cords[11])
<type 'tuple'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.