0

以下のコードについて助けが必要です。サンプルの入力と予想される出力がありますが、現在は何も印刷されていません。入力を提供してください。

基本的に、私のコードは 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()
4

1 に答える 1

1

リストを、内包表記を使用してnumrefs呼び出される dict に変換できます。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行は、この dict を構築します。

{202089: 'nums/89/202089/4',
 203455: 'nums/94/203455/6',
 205739: 'nums/39/205739/2'}
于 2012-12-29T04:03:39.897 に答える