简体   繁体   中英

How do I pick out first number in a print list and put it into an equation?

I have a program that works on a logfile to narrow it down to two items. That is as far as I have gotten and that is where my program stops, shown below. But I need to put the first of the two items into an equation and put the second item into a different equation. How can I do that?

import pylab  
from pylab import *  
from numpy import *  
from collections import Counter  

list_of_files=[('logfile.txt', 'F')]  
datalist = [( pylab.loadtxt(filename), label ) for filename, label in list_of_files]  
for data, label in datalist:    

      print [k for k,v in Counter(data[:,1]).items() if v>1 and 1500<=k<2200]

When I run above program it will print something like [1685, 1650]

So I now need to add onto above program so that it automatically puts the first number, 1685, into an equation and then put the second number, 1650, into a different equation and print the results.

You can't pick out a value from something you printed. Once you print it, it's forgotten.

You have to store the thing in a variable. Then you can pick it out easily.

For example, instead of this:

print [k for k,v in Counter(data[:,1]).items() if v>1 and 1500<=k<2200]

Do this:

thingies = [k for k,v in Counter(data[:,1]).items() if v>1 and 1500<=k<2200]
print thingies
print first_equation(thingies[0])
print second_equation(thingies[1])

You're using a Counter to build your results. A Counter , like a dict , has no order.* If you add a , then b , then c , you might get back a , then c , then b , or any of the other 5 permutations.

If you need to preserve the original order, you have to take care of that manually. You can do that by using a separate "key list", iterating k in keylist instead of k, v in counter.items() , and using counter[k] in place of v . Or, more simply, just build an OrderedCounter out of OrderedDict and Counter (as shown in the recipes in the docs), and use that:

thingies = [k for k,v in OrderedCounter(data[:,1]).items() if v>1 and 1500<=k<2200]

On the other hand, if you need the end results in some sorted order, you can just sort them after the fact:

thingies = sorted(k for k,v in Counter(data[:,1]).items() if v>1 and 1500<=k<2200)

In your case, you want "the higher value number is [0]", which sounds like you want them sorted, but in reverse order. So:

thingies = sorted((k for k,v in Counter(data[:,1]).items() if v>1 and 1500<=k<2200),
                  reverse=True)

* Of course this isn't really true; they do have some order. But the order is generally not useful, and not worth knowing about, beyond the fact that iterating the same dict repeatedly with no changes in between will always get the same order.

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