简体   繁体   中英

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

I have a list like this :

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')]

From this list, I wrote code for max and min values of X , Y and Z .

However, I also want to print that If I remove the pairs of X then X will not be in the list and it should print that "X is Empty". same if there are pairs for AZ in which A,B,G,S,X and so on are not in list then this should print like "A is Empty.. B is Empty.. G is Empty..S is Empty..X is Empty.."Also should print the min and max values of remaining those are in list..

This is my code in 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)

I would use a dictionary to hold the values for each character:

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

processed = {}

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

Then iterate through all ASCII uppercase characters, printing either the calculated values or eg "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])))

You could simplify slightly with collections.defaultdict :

from collections import defaultdict

processed = defaultdict(list)

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

Generally, I would suggest breaking up your program a bit - separate the import of tuple data from a text file into one function, and processing the list into another. This makes it easier to develop and test each in isolation.

I would do something like:

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))

That should work very nicely. The code above is not formatted to have a pretty output, but that is just a matter of you playing with the print functions a little.

If you use a defaultdict to hold the values you've read it may be easier

from collections import defaultdict
items = defaultdict(list)

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

then you'll end up with only a single key in the dictionary for each element and you can delete any element values simply by using

del items['X']

and you can use

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

You can use set with filter:

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)

Output:

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. First get unique keys from dataset
  2. Form list from keys
  3. pass the list to max function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM