簡體   English   中英

如何根據Python列表中存在的值從列表中刪除字典?

[英]How do I remove a dictionary from a list depending on a value being present in a list in Python?

我是Python的新手,所以如果我的代碼不是以最“ pythonic”的方式編寫的,請提前道歉。

我正在將CSV文件上傳到腳本,並且如果該行符合特定條件,我想過濾該CSV文件。

我有兩個列表, a_lstb_lst 一旦字典位於a_lst ,我將檢查a_lst是否存在具有相應key:value的b_lst 如果有匹配項,則將其打印到控制台。 我不想打印到控制台,而是要從a_lst刪除該項目。 我該怎么做呢?

a_lst = []
b_lsts = []

with open(file_name, 'rt') as f:
        reader = csv.DictReader(f)
        for row in reader:
            if row['Minutes'] == '0' and row['MB'] == '0' and row['Calls'] == '1':
                a_lst.append(row)
            elif row['Minutes'] == '0' and row['MB'] == '' and row['Calls'] == '1':
                a_lst.append(row)
            elif row['Minutes'] == '' and row['MB'] == '0' and row['Calls'] == '1':
                a_lst.append(row)
            elif row['Minutes'] == '' and row['MB'] == '' and row['Calls'] == '1':
                a_lst.append(row)
            else:
                b_lst.append(row)

i = 0
while i < len(a_lst):
    if not any(d['Name'] == a_lst[i]['Name'] for d in b_lst):
        print a_lst[i]['Name']+"(Row"+str(i)+") is not b_lst."
    else:
        print a_lst[i]['Name']+"(Row"+str(i)+") is present."
            i+=1

編輯 :我想要的結果

Name, PhoneNo, Minutes, MB, Calls
Steve,0777777777,0,0,1
Steve,0777777777,0,2,14
Steve,0777777777,0,0,1
John,078888888,0,0,1
John,078888888,0,0,1
John,078888888,0,0,1
Dave,07999999,2,3,4
Dave,07999999,2,6,24

如果上面的數據是我的插入內容,那么我只想看到John的名字,因為他是唯一一個在他的名字的所有行中都包含值“ 0,0,1”的人

剛剛從列表中刪除的元素,如果它具有相同的鍵/值,你也想去掉notany作為,我們要刪除,如果有任何的比賽:

for ele in a_lst[:]:
    if  any(d['Name'] == ele['Name'] for d in b_lst):
        a_lst.remove(ele)

或者只是在添加之前忘記使用any和filter,將row['Name']到集合中並檢查是否已經看到它:

seen = set()
with open(file_name, 'rt') as f:
        reader = csv.DictReader(f)
        for row in reader:
           if row['Name'] in seen:
               continue
           if all((row['Minutes'] == '0', (row['MB'] == '0' or not row['MB']), row['Calls'] == '1')):
               a_lst.append(row)
           elif all((not row['Minutes'], (row['MB'] or not row['MB']), row['Calls'] == '1')):
                a_lst.append(row)
           else:
               seen.add(row['Name']) 
         # remove "else:" and just use seen.add(row['Name']) outside the elif if you want all dups removed

根據您的編輯:

seen = set()
with open(infile, 'rt') as f:
    reader = csv.reader(f,delimiter=",")
    for row in reader:
        if row[0] in seen:
            continue
        if all(x in {"0", "1"} for x in row[2:]):
            print(row)
        seen.add(row[0])

輸出:

['Steve', '0777777777', '0', '0', '1']
['John', '078888888', '0', '0', '1']

SteveJohn的相對列都只有0和1。

如果只希望在其列中專門包含0和1的名稱:

from collections import defaultdict
d = defaultdict(list)

with open(infile, 'rt') as f:
    reader = csv.reader(f,delimiter=",")
    for row in reader:
        d[row[0]].append([row, set(row[2:])])

print([v[0][0] for k, v in d.items() if all(sub[1] == {"0","1"} for sub in v)])

[['John', '078888888', '0', '0', '1']]

或使用集合(如果您的姓名始終分組在一起):

seen = set()
temp = set()

with open(infile, 'rt') as f:
    reader = csv.reader(f,delimiter=",")
    next(reader)
    prev = None
    for row in reader:
        # found new name and it is not the first
        if row[0] not in seen and temp:
            # set should only hav  and 1 if all columns only contain 0,1
            if temp == {"0", "1"}:
                print(prev)  # print previous row
            # reset temp
            temp = set()
        seen.add(row[0])
        temp.update(row[2:])
        # need to keep track of previous row 
        prev = row

輸出:

['John', '078888888', '0', '0', '1']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM