Python list index out of range on return value of split

前端 未结 4 716
南笙
南笙 2021-01-18 11:22

I\'m writing a simple script that is trying to extract the first element from the second column of a .txt input file.

import sys

if (len(sys.argv) > 1):         


        
4条回答
  •  长情又很酷
    2021-01-18 11:39

    When you are working with list and trying to get value at particular index, it is always safe to see in index is in the range

    if len(list_of_elements) > index: 
       print list_of_elements[index]
    

    See:

    >>> list_of_elements = [1, 2, 3, 4]
    >>> len(list_of_elements)
    4
    >>> list_of_elements[1]
    2
    >>> list_of_elements[4]
    Traceback (most recent call last):
      File "", line 1, in 
    IndexError: list index out of range
    >>> 
    

    Now you have to find out why your list did not contain as many elements as you expected

    Solution:

    import sys
    
    if (len(sys.argv) > 1):
        f = open(sys.argv[1], "r")
        print "file opened"
    
    for line in f:
        line = line.strip().strip('\n')
        # Ensure that you are not working on empty line
        if line:
            data = line.split(",") 
        # Ensure that index is not out of range
        if len(data) > 1: print data[1]
    
    f.close()
    

提交回复
热议问题