简体   繁体   中英

Python: How to iterate over specific columns in rows in text file

I would like to iterate a script along columns in a text file but ignoring the first 5 columns.

Currently my script runs through a text file row by row assessing the values in column 6. I would like it to then run through all the rows assessing column 6, then column 7, then column 8 etc I DO NOT want to assess each column for every row as the script reads through the file, but to run through the entire file assessing column n and then repeat for column n + 1

Currently I have the simple:

for line in Input:
    line = line.rstrip() 
    fields = line.split("\t")
    for col in row:

but I'd like to specify that it ignores the first 5 columns, as these are not targets (but are still needed as information in the file).

I guess something like for col in row for range 6:20 might work, but I am a python beginner and don't know the correct way to express this in python. Please let me know how I can clarify the question if it is too confusing.

Thank you in advance for your help.

Best,

Rubal

If you have a list row , then row[a:b] is the range of elements starting with element number a and up to but not including element number b .

For example:

row = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']

print row[2:4]

The output of this would be

['gamma', 'delta']

And so in a loop you can write:

for col in row[6:20]:
    foo()

Alternatively, loop to the end of the list with

for col in row[6:]:
    foo()
for line in Input:
    line = line.rstrip() 
    fields = line.split("\t")
    for col in fields[5:]:
        # process

Without copying

for line in Input:
    line = line.rstrip() 
    fields = line.split("\t")
    for index in range(5, len(fields)):
        #do_smth with fields[index]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM