简体   繁体   中英

Applying a certain change to all elements in a list ( Python )

I'm working on a human stats database for a simulation game and cannot figure out a certain function. The data about each person is stored as a string in a humandict list. Every in-game year the ageup() func should be called, and change each strings data value.

This is the string data format that i use ( the list consists of these values which store data about every human ):

##ID, age, strengths, smarts

I call the .split() method in order to divide those different numbers in a string to a list, and apply int() to each list item in order to use them in math. The ageup() function should access every humandict item and change the age value by 1. This is the code I currently use ( which doesn't work as intended ):

    for unit in humandict:
        human = unit.split()
        age = int(human[1])
        age += 1
        replace = (str(human[0])+" "+str(age)+" "+str(human[2])+" "+str(human[3]))
        humandict[int(human[0])] = replace
    print(humandict)

The code successfully runs once, and the next time the function is called I then get the following error:

File "main.py", line 15, in ageup
    human = unit.split()
AttributeError: 'NoneType' object has no attribute 'split'

I simply don't understand where the problem is arising, it can due to wrong ID assignment or something else. But I know for sure that using dictionary here is a better and efficient way to handle data.

So here is how you can implement the same stuff with dictionary:

human_list_of_dict = [{'ID':<int>, 'age':<int>, 'strengths':<str>, 'smarts':<str>}]

above written is a list of dictionary to store data right now it has only 1 dictionary in it but there can be as much as you need. then you simple call it just like a list with few changes.

for unit in human_list_of_dict:
    unit['age'] = unit['age']+1

By this way you can save you hassle of converting string to list and vice-versa. Also code is efficient this way(since there is less data manipulation).

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