0

我在下面的代码上需要一些帮助,我有示例输入和预期输出,目前它没有打印任何东西..请提供您的输入,

基本上我的代码正在解析 num_ids.txt 中的值并检查每个值是否大于提供的 base_num 值以及该值是否不在“num_ignore”列表中,然后(在满足前两个条件后)它尝试匹配 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()
4

1 回答 1

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'}
于 2012-12-29T04:03:39.897 回答