这里实际上发生了几件事。
首先,您不能将字符串与整数进行比较。例如:
my_str = "65"
print(my_str < 65) # <-- RESULTS IN A `TypeError`
这就是为什么我们确切地知道您的数据结构是什么非常重要的原因之一。仅仅说它是一个元组、列表或字典是不够的。我建议查看How to create a Minimal, Complete, and Verifiable example。
话虽如此,鉴于您正在拆分一个字符串,我们可以假设迭代列表返回的值也是一个字符串,但这可能不是实现您想要做的最有效的方法。
其次,您的代码中有错字。我假设您正在尝试测试 LatA 是否小于零,LatB 是否大于零,LongA 是否大于 65,并且 LongB 是否小于 70;但是您的 if 语句正在测试 LongA 是否大于 65 且小于 70。
第三,您上面的代码实际上不是有效代码,您的问题的简短回答是“是”还是“否”,具体取决于您要测试的内容以及所需的结果。例如:
llist = [
"item1, -5, 70, 5, 65", # MEETS CRITERA
"item2, 5, 60, -5, 75", # DOES NOT MEET CRITERA
]
match_found = False
value = ""
for lstr in llist:
ldata = lstr.split(',')
item = ldata[0]
LatA = int(ldata[1])
LongA = int(ldata[2])
LatB = int(ldata[3])
LongB = int(ldata[4])
if LatA < 0 and LatB > 0 and LongA > 65 and LongB < 70:
# This will get reassigned on each match. Try using
# value += {item}. There is also no need for a dict,
# you could simply use a *list* (not tuple).
value = {item}
print("Match Found")
match_found = True
if not match_found:
print("No Match Found")
会提供一个基本的“是的,在整个数据结构中找到单个匹配”,但会为您的每个条目连续打印“找到匹配”列表符合您的标准并重新分配变量value。除非绝对需要,否则可以通过删除 print 语句来避免这种情况。也许更好的方法是使用字典,例如:
# [LatA, LongA, LatB, LongB]
my_dict = {
"Location #1": [-5, 70, 5, 65],
"Location #2": [5, 60, -5, 75],
}
my_matches_list = []
for location, coords in my_dict.items():
if coords[0] < 0 and coords[1] > 65 and coords[2] > 0 and coords[3] < 70:
my_matches_list.append(location)
if my_matches_list:
print("Matches Found:")
for match in my_matches_list:
print(" - ", match)
else:
print("No Matches Found")
# Matches or No Matches Found Response...
# print("Matches Found" if my_matches_list else "No Matches Found")
填充my_matches_list 后,您可以使用这些值与您的字典进行比较。但是,这可能不是您想要的,但它甚至可以消除多个列表或字典以帮助减少混淆。
最后,如果您需要保持您的代码与您发布的大致相同,并且您需要比 yes 或 no 更实用的结果,您可以执行以下操作:
llist = [
"item1, -5, 70, 5, 65", # MEETS CRITERA
"item2, -1, 75, 10, 15", # MEETS CRITERA
"item3, 5, 60, -5, 75", # DOES NOT MEET CRITERA
]
matched_values = list()
for lstr in llist:
ldata = lstr.split(',')
item = ldata[0]
LatA = int(ldata[1])
LongA = int(ldata[2])
LatB = int(ldata[3])
LongB = int(ldata[4])
if LatA < 0 and LatB > 0 and LongA > 65 and LongB < 70:
matched_values.append(item) # += [item] works too, but not preferred.
if matched_values:
print("Matches Found:")
for match in matched_values:
print(" - ", match)
else:
print("No Matches Found")
这将简单地测试matched_values 列表以查看它是否有一个值,该值将提供真或假结果。