[Tutor] Getting range of a list

Hs Hs ilhs_hs at yahoo.com
Tue Feb 5 22:48:10 CET 2013


Thanks Steve. 

But one question, when I print, I get extra empty lines. How to get rid of them!  Thanks again.
>>> f = open('test')
>>> head = '---'
>>> for line in f:
if line.startswith('>'):
head = line[1:].strip()
else:
print head+'\t'+line

X1A
                        <------
X1G
                       <-----
X2A

X2G

X3A

X3G

X4A

X4A

Thanks
Hs.



________________________________
 From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org 
Sent: Tuesday, February 5, 2013 4:28 PM
Subject: Re: [Tutor] Getting range of a list
 
On 06/02/13 08:08, Hs Hs wrote:

> Here is what I do :
>>>> f1 = open('test','r')
>>>> da = f1.read().split('\n')
>>>> dat = da[:-1]
>>>> dat
>>>> mpos = []
> 
>>>> for i in range(len(dat)):
> if dat[i].startswith('>'):
> mpos.append(i)
> 
>>>> mpos
> [0, 3, 6, 9]
> 
>>>> for item in range(len(mpos)):
> start = mpos[item]
> enda = item+1
> end  = mpos[enda]-1
> head = dat[start]
> block  = dat[start+1:end]
> for i in block:
> print head+'\t'+i


You are thinking like a C programmer, not a Python programmer. You should almost never need to iterate over a range of numbers like this.

Instead, try something like this:

f = open('test')
head = '----'
for line in f:
    if line.startswith('>'):
        head = line[1:].rstrip()  # remove trailing newline
    else:
        print head + '\t' + line

f.close()



In general, you should iterate over collections of data directly. For example:

# WRONG
for i in range(len(data)):
    x = data[i]
    print x

# RIGHT
for x in data:
    print x



# WRONG
for i in range(len(data)):
    x = data[i]
    if x == 'spam':
        data[i] = 'ham'

# RIGHT
for i, x in enumerate(data):
    if x == 'spam':
        data[i] = 'ham'



Hope this helps.



-- Steven
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130205/922290ae/attachment-0001.html>


More information about the Tutor mailing list