我需要一些关于下面代码的帮助,我有样本输入和预期输出,当前它没有打印任何东西..请提供你的输入,
基本上我的代码是解析num_ids.txt中的值并检查每个值是否大于提供的base_num值,如果该值不在“num_ignore”列表中,然后(在满足前2个条件之后),它会尝试匹配numrefs列表并在numrefs ...
中打印匹配的值EXPECTEDOUTPUT:-
nums/39/205739/2
import os
import subprocess
def p4 (base_num):
numrefs = ['nums/89/202089/4', 'nums/39/205739/2', 'nums/94/203455/6']
num_ignore = [150362, 147117]
'''
num_ids.txt
202089
205739
147117
203455
'''
with open('./num_ids.txt', 'rb') as f:
# Iterate over the file itself
for line in f:
num = int(line)
if num > base_num and num not in num_ignore and line in numrefs:
print numrefs
def main():
base_num=203456
p4(base_num)
if __name__ == '__main__':
main()
答案 0 :(得分:1)
您可以使用理解将numrefs
列表转换为名为numrefs_index
的词典。这样您就可以使用in
运算符并更快地访问引用。
def p4(base_num):
numrefs = ['nums/89/202089/4', 'nums/39/205739/2', 'nums/94/203455/6']
num_ignore = [150362, 147117]
numrefs_index = dict((int(x.split('/')[2]), x) for x in numrefs)
for line in file("num_ids.txt"):
num = int(line)
if num > base_num and num not in num_ignore and num in numrefs_index:
print numrefs_index[num]
if __name__ == "__main__":
p4(203456)
# prints:
# nums/39/205739/2
numrefs_index
行构建了这个词:
{202089: 'nums/89/202089/4',
203455: 'nums/94/203455/6',
205739: 'nums/39/205739/2'}