簡體   English   中英

如何從鍵值對列表中搜索數據是否在列表中

[英]How to Search data from a list of Key-Value pair that it is in list or not

我有一個這樣的列表:

a = [('X', '63.658'), ('Y', '21.066'), ('Z', '230.989'), 
     ('X', '63.424'), ('Y', '21.419'), ('Z', '231.06'), 
     ('X', '63.219'), ('Y', '21.805'), ('Z', '231.132'), 
     ('X', '63.051'), ('Y', '22.206'), ('Z', '231.202'), 
     ('X', '62.915'), ('Y', '22.63'), ('Z', '231.272'), 
     ('X', '62.811'), ('Y', '23.073'), ('Z', '231.341')]

從這個列表中,我為XYZ最大值和最小值編寫了代碼。

但是,我也想打印如果我刪除 X 對,那么 X 將不在列表中,它應該打印“X 為空”。 同樣,如果 AZ 的對中 A、B、G、S、X 等不在列表中,那么這應該打印為“A 為空.. B 為空.. G 為空..S 為空。 .X 是空的..”還應該打印列表中剩余的最小值和最大值。

這是我在 python 中的代碼:

 with open(r'/path of file...txt') as f:
        lines=f.readlines()
        lines=''.join(lines)
        lines=lines.split()
        a=[]
        for i in lines:
            match=re.match(r"([a-z]+)([-+]?[0-9]*\.?[0-9]+)",i,re.I)
            if match:
                a.append(match.groups())
    print a
    for tuples in a:
        key, value = tuples[0], float(tuples[1])
        groups[key].append(value)

    for key, values in groups.iteritems():
        print key, max(values), min(values)

我會使用字典來保存每個字符的值:

a = [('X', '63.658'), ('Y', '21.066'), ...]

processed = {}

for char, value in data:
    if char not in processed:
        processed[char] = []
    processed[char].append(value)

然后遍歷所有 ASCII 大寫字符,打印計算值或例如"N is empty..."

import string

for char in string.ascii_uppercase:
    if char not in processed:
        print("{0} is empty...".format(char))
    else:
        print("{0}: min={1}, max={2}".format(char, 
                                             min(processed[char]),
                                             max(processed[char])))

您可以使用collections.defaultdict稍微簡化:

from collections import defaultdict

processed = defaultdict(list)

for char, value in data:
    processed[char].append(value)

通常,我建議將您的程序稍微分解一下 - 將元組數據從文本文件導入到一個函數中,然后將列表處理到另一個函數中。 這使得單獨開發和測試每一個都更容易。

我會做這樣的事情:

from string import ascii_uppercase

elems = set(c for c, n in a)
for c in ascii_uppercase:  # Or whatever string of characters you want to check.
    if c in elems:
        relevant = [t for t in a if t[0] == c]
        print((c, max(relevant)[1], min(relevant)[1]))
    else:
        print((c, None))

那應該很好用。 上面的代碼沒有格式化為具有漂亮的輸出,但這只是您稍微使用print功能的問題。

如果您使用defaultdict來保存您已閱讀的值可能會更容易

from collections import defaultdict
items = defaultdict(list)

groups = match.groups()
items[groups[0]].append(float(groups[1]))

那么對於每個元素,您最終只會在字典中只有一個鍵,並且您可以通過使用簡單地刪除任何元素值

del items['X']

你可以使用

if 'X' not in items:
    print('X is empty')
else:
    values = items['X']
    avg = sum(values) / len(values)
    min = min(values)
    max = max(values)

您可以將 set 與過濾器一起使用:

k=set([i[0] for i in a])
for ki in k:
    l=filter(lambda x:x[0]==ki, a)
    print "max:", max(l), "min: ", min(l)

輸出:

max: ('Y', '23.073') min:  ('Y', '21.066')
max: ('X', '63.658') min:  ('X', '62.811')
max: ('Z', '231.341') min:  ('Z', '230.989')
  1. 首先從數據集中獲取唯一鍵
  2. 來自鍵的表單列表
  3. 將列表傳遞給 max 函數

暫無
暫無

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

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