everestial007 - 1 year ago 62
Python Question

# Access values from next line within for-loop to continue and break?

In the given data set I need to multiply values from different blocks with each other.

I want to access data from next line within for loop and then build the list and create a product if the block value matches but the examples I have looked so far isn't quite helping. Actually, this data is just a part of the big data and I need some explanation on any provided solution on how/why is it working.

`So,for X(set) I have to multiply: 0.25*0.1*0.83 (since they belong to same block`

``````block   X_set
2480    0.25
2480    0.1
2480    0.083
2651    0.43
2651    0.11
2651    0.23
``````

My code is as follows:

``````test_q = open("test_question.txt", "r+")

product=1.0
value_list = []

row = data_q.split("\n")

for line in row:
block = line.split("\t")
X_list = block[1].split()
X_value = float(block[1])
value_list = value_list + X_list
product = product*X_value

print(value_list)
print(product)
``````

The result is:

``````['0.25', '0.1', '0.083', '0.43', '0.11', '0.23']
2.2573925000000003e-05
``````

But, in the print I want

``````['0.25', '0.1', '0.083']
0.0002075

['0.43', '0.11', '0.23']
0.010879
``````

So, I want to access the index value from the next line so the for-loop can continue or break.

I have tried using to access the block value from next line:

``````    for i in range(0, len(row)-1):
next_line = row[i+1]
``````

How, can I improve this code?

So, how to inject the break and continue function within this for-loop?

• I don't want to use a fixed value for blocks since this is a long file and the block value will change.

• Also, the row with same block values may not be next to each other.

• Also, i don't need solution on pandas since this is just a part of big file which is exclusive mined using for-if-else loop.

Thanks much in advance !

``````from collections import defaultdict
from functools import reduce
from operator import mul

res = defaultdict(list)
with open('file') as f:
for r in f:
k, v = r.split()
res[k].append(v)

for v in res.values():
print(v)
print(reduce(mul, (float(f) for f in v), 1))
``````

your problem is that you'd have to check every row to find a match, which would be a pain. it's easier just to store in a dict and then print out the results at the end. (if you care about order, you can use an `OrderedDict`)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download