简体   繁体   中英

Parsing a list of lists and manipulating it in place

So I have a list of lists that I need to parse through and manipulate the contents of. There are strings of numbers and words in the sublists, and I want to change the numbers into integers . I don't think it's relevant but I'll mention it just in case: my original data came from a CSV that I split on newlines, and then split again on commas.

What my code looks like:

def prep_data(data):
    list = data.split('\n') #Splits data on newline
    list = list[1:-1] #Gets rid of header and last row, which is an empty string

    prepped = []
    for x in list:
        prepped.append(x.split(','))

    for item in prepped: #Converts the item into an int if it is able to be converted
        for x in item:
            try:
                item[x] = int(item[x])
            except:
                pass
    return prepped

I tried to loop through every sublist in prepped and change the type of the values in them, but it doesn't seem like the loop does anything as the prep_data returns the same thing as it did before I implemented that for loop.

I'm not sure about your function, because maybe I didn't understand your income data, but you could try something like the following because if you only pass, you could lose string or weird data:

def parse_data(raw_data):
    data_lines = raw_data.split('\n') #Splits data on newline
    data_rows_without_header = data_lines[1:-1] #Gets rid of header and last row, which is an empty string

    parsed_date = []
    for raw_row in data_rows_without_header:
        splited_row = raw_line.split(',')
        parsed_row = []
        for value in splited_row:
            try:
                parsed_row.append(int(value)
            except:
                print("The value '{}' is not castable".format(value))
                parsed_row.append(value) # if cast fails, add the string as it is
        parsed_date.append(parsed_row)
    return parsed_date

I think I see what is wrong, you are thinking python is more generous with it's assignment than it actually is.

def prep_data(data):
list = data.split('\n') #Splits data on newline
list = list[1:-1] #Gets rid of header and last row, which is an empty string

prepped = []
for x in list:
    prepped.append(x.split(','))

for i in prepped: #Converts the item into an int if it is able to be converted
item = prepped[i]
    for x in item:
        try:
            item[x] = int(item[x])
        except:
            pass
prepped[i] = item
return prepped

I can't run this on the machine I'm on right now but it seems the problem is that "prepped" wasn't actually receiving any new assignments, you were just changing values in the sub array "item"

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