I have the following question, for which I can't seem to find an answer. My python knowledge is basic and i'm working with version 2.7.2 and 2.6.5 right now.
Let's say I have the following list:
list1 = [1642842,780497,1506284,1438592,1266530,1154853,965861,610252,1091847,1209404,1128111,749998]
I want to know the factor difference for each 2 items (item 0,1 item 1,2 item 2,3 etc).
The output should be like this (but preferable rounded up to 1 decimal):
list2 = [2.1048665145,0.5181605859,1.047054342,1.1358530789,1.0967023509,1.195672048, 1.5827248415,0.5589171377,0.9027975763,1.0720611713,1.5041520111]
The final result I'm looking for is that when the factor is more than 1.5, I want to report the 2 list items numbers and their factor value.
item 0,1 value 2.1
item 6,7 value 1.6
item 10,11 value 1.5
How should I do this?
Finding the numeric difference can be easily done with:
print numpy.diff(list1)
or
for i in (abs(x - y) for (x, y) in zip(list1[1:], list1[:-1])):
print i
But i'm breaking my head to find a sollution for my question above? I tried a few things with the above code, but I can't seem to get a good result.
Also note that although I will filter the data in list1 first, it will contain upfollowing zero values which gave me dividebyzero problems before.
EDIT: Thanks for the solutions, most of them do exactly what I want. Unfortunately the items in these lists have a fixed position. This information, I can't discard, so filtering some of the items out of the list to prevent errors like 'ZeroDivisionError: float division by zero' is not really an option. To explain a bit more, there are likely to be lists of the following format:
list1 = [0,0,0,0,0,0,0,0,2,5,65,456,456456,456564,456666,666666,2344,233,232,122,88,6,0,0,0,0]
What is a pythonic way with any of the solutions below to address this issue? To be a bit more specific about the output:
item 0,1 value 0
item 1,2 value 0
item 2,3 value 0
etc.
item 8,9 value 2.5
item 9,10 value 13
etc.
Last edit: I'll filter the data anyway instead of creating problems to fix. Thanks for the answers all!
Using the pairwise
function from the itertools recipe:
import itertools
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
diff = [round(abs(x/float(y)), 1) for x, y in pairwise(your_iterable)]
One possible way:
list1 = [1642842,780497,1506284,1438592,1266530,1154853,965861,610252,1091847,1209404,1128111,749998]
list2 = [(i, a, b, (1.0*a)/b) for (i, (a, b)) in enumerate(zip(list1, list1[1:]))]
for i, a, b, f in filter(lambda (i, a, b, f): f > 1.5, list2):
print 'item {0} ({1}), {2} ({3}) value {4:.1f}'.format(i, a, i+1, b, f)
Output:
item 0 (1642842), 1 (780497) value 2.1
item 6 (965861), 7 (610252) value 1.6
item 10 (1128111), 11 (749998) value 1.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With