我有一个python字典,其值为列表列表:
android:layout_weight="1"
请注意,可以在不同的键中重复一个数字,在这种情况下为17。
我有一个文本文件,格式如下:
dictionary={'sca4': [['BM1', 17], ['BM2', 33]], 'sca6': [['GM2', 46], ['GM2', 67], ['BM2', 17]]}
我按如下方式解析了文本文件:
sca4 15 25
sca4 20 32
sca6 45 62
我想看看字典中每个列表的第二个元素(即17,33,46,67)是否都在文本文件的col2和col3的间隔范围内,并带有以下代码:
for line in textfile.split("\n"):
if not line.strip():
continue
col1, col2, col3 = line.strip().split(" ")
获得输出:
for value_list in dictionary.get(col1, []):
if int(col2) <= value_list[1] <= int(col3):
print "withinrange"
else:
print "outsiderange"
我既没有输出也没有任何错误。如果可以对我的代码进行评论以及如何调试它将会很棒。
答案 0 :(得分:2)
试试这段代码:
file = open("test1.txt")
textfile = file.readlines()
dict={'sca4': [['BM1', 17], ['BM2', 33]], 'sca6': [['GM2', 46], ['GM2', 67]]}
dict1 = {}
l =[]
for line in textfile:
if not line.strip():
continue
col1, col2, col3 = line.strip().split(" ")
for value_list in dict.get(col1, []):
#print value_list[1]
if not (value_list[1] in l):
l.append(value_list[1])
if ((int(col2) <= value_list[1]) and (value_list[1] <= int(col3))):
dict1[value_list[1]] = 'correct'
for l1 in l:
if dict1.has_key(l1):
print "withinrange"
else:
print "outsiderange"
答案 1 :(得分:0)
实际上你的程序是通过以下数据进行的:
'sca4':
[['BM1', 17], in interval(15, 25) -> "correct"
['BM2', 33]], in interval(15, 25) -> "wrong"
'sca4':
[['BM1', 17], in interval(20, 32) -> "wrong"
['BM2', 33]], in interval(20, 32) -> "wrong"
'sca6':
[['GM2', 46], in interval(45, 62) -> "correct"
['GM2', 67]] in interval(45, 62) -> "wrong"
答案 2 :(得分:0)
另一种编码风格:
import sys
dictionary = {'sca4': [['BM1', 17], ['BM2', 33]], 'sca6': [['GM2', 46], ['GM2', 67]]}
sys.path.append('C:\\Users\\AmmourKx\\Documents\\Python\\StackOverFlow')
text = open(sys.path[-1] + '\\2.txt')
for line in text:
print line
l = line.strip().split(' ')
print l
for i in range(len(dictionary.values())):
if dictionary.get(l[0])[i][1] >= int(l[1]) and dictionary.get(l[0])[i][1] <= int(l[2]):
print 'Within Range'
else:
print 'Outside Range'
text.close()
答案 3 :(得分:0)
添加了另一个答案,其中包含上一个发布的答案的评论中指定的额外要求:
def printList(l, dict1):
for l1 in l:
if dict1.has_key(l1):
print "withinrange"
else:
print "outsiderange"
file = open("test1.txt")
textfile = file.readlines()
dict={'sca4': [['BM1', 17], ['BM2', 33]], 'sca6': [['GM2', 46], ['GM2', 67], ['BM',17]]}
dict1 = {}
l =[]
key = ''
for line in textfile:
if not line.strip():
continue
col1, col2, col3 = line.strip().split(" ")
if not (key == col1):
printList(l, dict1)
l =[]
key = col1
dict1 = {}
for value_list in dict.get(col1, []):
#print value_list[1]
if not (value_list[1] in l):
l.append(value_list[1])
if ((int(col2) <= value_list[1]) and (value_list[1] <= int(col3))):
dict1[value_list[1]] = 'correct'
printList(l, dict1)