简体   繁体   中英

I cannot get split to work, what am I doing wrong?

Here is the code for the program that I have done so far. I am trying to calculate the efficiency of NBA players for a class project. When I run the program on a comma-delimited file that contains all the stats, instead of splitting on each comma it is creating a list entry of the entire line of the stat file. I get an index out of range error or it treats each character as a index point instead of the separate fields. I am new to this but it seems it should be creating a list for each line in the file that is separated by elements of that list, so I get a list of lists. I hope I have made myself understood.

Here is the code:

def get_data_list (file_name):
    data_file = open(file_name, "r")
    data_list = []
    for line_str in data_file:

        # strip end-of-line, split on commas, and append items to list
        line_str.strip()       
        line_str.split(',')

        print(line_str)

        data_list.append(line_str)
        print(data_list)                






file_name1 = input("File name: ")
result_list = get_data_list (file_name1)


print(result_list)

I do not see how to post the data file for you to look at and try it with, but any file of numbers that are comma-delimited should work.

If there is a way to post the data file or email to you for you to help me with it I would be happy to do so.

Boliver

Strings are immutable objects, this means you can't change them in place. That means, any operation on a string returns a new one. Now look at your code:

line_str.strip()            # returns a string      
line_str.split(',')         # returns a list of strings
data_list.append(line_str)  # appends original 'line_str' (i.e. the entire line)

You could solve this by:

stripped = line_str.strip()
data = stripped.split(',')
data_list.append(data)

Or concatenating the string operations:

data = line_str.strip().split(',')
data_list.append(data)

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