2
\$\begingroup\$

I have a file, the content is in the format of

41545
0
0
1
2
3
3
3
...

Following is the code

X=[]
Y=[]
total=0
count=0
for line in open(file,'r'):
    count+=1
    line=line.strip()
    if(line.strip()):
        if(count==1):
            total=int(line)
        else:
            X.append(count-1)
            Y.append(int(line))

the output for the above code is

total=41545 #first line
X=[1,2,3,4,5,6,7] #count of second line onwards
Y=[0,0,1,2,3,3,3] #second line onwards information

Is there a shorter and hopefully more efficient code that can achieve the same purpose?

\$\endgroup\$

migrated from stackoverflow.com Oct 13 '14 at 12:42

This question came from our site for professional and enthusiast programmers.

3
\$\begingroup\$

Build a generator over the file to return just ints, then transpose the enumeration to get your X and Y, eg:

with open('testing.txt') as fin:
    lines = (int(line) for line in fin)
    total = next(lines)
    X, Y = zip(*enumerate(lines, 1))

Note X and Y will be tuples instead of lists, but you can convert them after if you wish.

\$\endgroup\$
  • \$\begingroup\$ clean and efficient \$\endgroup\$ – Anzel Oct 9 '14 at 16:31
0
\$\begingroup\$

There certainly is!

Try this:

Y=[]

with open(file, 'r') as fd:
    total = int(fd.readline().strip())

    for line in fd:
        line=line.strip()
        if(line):
            Y.append(int(line))

X is superfluous because it my be calculated by

pos = 4 #Index of an element in Y
y_value = Y[pos]
x_value = pos + 1 #X value of that element

Where pos is the index of an element of Y that you would like the X value for

\$\endgroup\$
0
\$\begingroup\$

This should do the trick. Read the first line by itself and convert to int. Then read the remaining lines via list comprehension. Then you can just generate the line numbers based on the number of values read in.

with open(file, 'r') as f:
    total = int(f.readline().strip())
    Y = [int(i) for i in f.readlines()]
    X = list(range(1,len(Y)+1))
\$\endgroup\$
  • \$\begingroup\$ This is great, except that readlines() is not efficient and I think you swapped X and Y. \$\endgroup\$ – ErlVolton Oct 9 '14 at 16:15
  • \$\begingroup\$ Oops I did indeed flip X and Y. \$\endgroup\$ – Cyber Oct 9 '14 at 16:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.