繁体   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