문제

Say I have the following CSV file;

1.41, 123456
1.42, 123456
1.43, 123456

and i want to find the "position"/location of a value in row 0 i.e. "1.41, 1.42, 1.43" in this case, depending on whether the particular row value is greater than or equal to an arbitrary inputted value.

So for example if the inputted value was 1.42, we would return position 0 and 1, or if the inputted value was 1.4, we would return 0, 1 and 2. Likewise, if the value was 1.45 we would not return any positions. Here is what i have:

out = open("test.csv","rU")
dataf=csv.reader(out, delimiter=',')

for row in dataf:
    x = row[0]


    for i in xrange(len(x)):
    if x[i] >=1 :
        print i

only to get,

0
1
2
3
0
1
2
3
0
1
2
3

so then i use

for i in xrange(len(x)):
if x[i] >=2 :
    print i

But i still get the same position values. Can anyone steer me in the right direction?

도움이 되었습니까?

해결책

From what I can gather, this does what you're asking...

#!/usr/bin/env python

import csv

value = 1.42

out = open("test.csv","rU")
dataf=csv.reader(out, delimiter=',')
matches = [float(row[0]) >= value for row in dataf]
matches.reverse()

for i,m in enumerate(matches):
    if m: 
        print i

matches is a list of boolean values, that shows whether the first column in each row is greater than value. It looks like you want to order from the bottom up, so I reversed the list. The loop prints the index of the (reversed) list if the value in the first column was greater than or equal to value.

value = 1.42
output:

0
1

value = 1.4
output:

0
1
2

value = 1.45
no output.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top