第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

過濾txt文件在python中滿足某些條件?

過濾txt文件在python中滿足某些條件?

我有一個(gè)包含subjectid_num_[dog/cat]_[option]的 txt 文件。ID1_0123_CAT_ANIMAL_3ID1_0123_CAT_ANIMAL_GOOD_3ID1_0123_ABC_3ID2_1234_CAT_ANIMAL_3ID2_1234_CAT_ANIMAL_GOOD_3ID2_1234_DOG_ANIMAL_2ID2_1234_DOG_ANIMAL_GOOD_0ID2_1234_ABCD_3ID3_4321_DOG_ANIMAL_1ID3_4321_DOG_ANIMAL_GOOD_4ID3_4321_DOG_3我想過濾文件以獲得滿足條件的輸出。例如,下面的代碼將文件的輸出具有CAT和GOOD的名義,并且不包含DOG與GOOD在名稱中。名稱由相同subject_id和相同的數(shù)字確定num。但是,代碼沒有顯示我的預(yù)期輸出。我該如何解決?這是我的代碼with open("./cat_dog.txt", 'r') as f:    files_list = [line.rstrip('\n') for line in f]file_filter = []for i, cat in enumerate(files_list):    if 'GOOD' in cat and 'CAT' in cat:        subject_id = cat.split('_')[0]        num_id = cat.split('_')[1]        subject_num = subject_id + '_' + num_id        for j, dog in enumerate(files_list):                if subject_num in dog and 'GOOD' in dog:                    if 'GOOD' in dog and 'DOG' in dog:                        continue;                    else:                        file_filter.append(cat)當(dāng)前輸出為ID1_0123_CAT_ANIMAL_GOOD_3ID2_1234_CAT_ANIMAL_GOOD_3雖然預(yù)期是ID1_0123_CAT_ANIMAL_GOOD_3
查看完整描述

1 回答

?
互換的青春

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊

你的代碼是錯(cuò)誤的。考慮ID2_1234_CAT_ANIMAL_GOOD_3在內(nèi)循環(huán)中檢查行時(shí)會(huì)發(fā)生什么:


subject_id = cat.split('_')[0]            #ID2

num_id = cat.split('_')[1]                # 1234

subject_num = subject_id + '_' + num_id   #ID2_1234

for j, dog in enumerate(files_list):

        # when dog is the line ID2_1234_CAT_ANIMAL_GOOD_3

        if subject_num in dog and 'GOOD' in dog:   # this is true

            if 'GOOD' in dog and 'DOG' in dog:   # this is false

                continue;

            else:

                file_filter.append(cat)   # then it outputs it

問題是,每行GOOD,并CAT在將“匹配本身”的內(nèi)循環(huán)。


恕我直言,我會(huì)使用itertools.groupby。類似的東西:


from itertools import groupby


def key(line):

    return line.split('_')[:2]


for key, lines in groupby(sorted(files_list, key=key), key=key):

    good_lines = [line for line in lines if 'GOOD' in line]

    if len(good_lines) == 1 and 'CAT' in good_lines[0]:

        file_filter.append(good_lines[0])

這也應(yīng)該是更有效的 O(nlog n) 與 O(n^2) 相比,盡管它需要 RAM 中文件的所有內(nèi)容。


如果您有除CATand以外的其他“類” ,DOG并且您想輸出GOOD CAT除subject_idis之外的所有行,GOOD DOG您可以通過以下方式修改上面的代碼:


is_good_cat = any('CAT' in line for line in good_lines)

is_good_dog = any('DOG' in line for line in good_lines)

if is_good_cat and not is_good_dog:

    file_filter.extend(line for line in good_lines if 'CAT' in good_lines)

(你需要使用.extend和循環(huán),因?yàn)槲覀儾辉僦酪獙懩囊恍?,所以你必須過濾它們。


查看完整回答
反對(duì) 回復(fù) 2021-11-09
  • 1 回答
  • 0 關(guān)注
  • 239 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)