[英]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.我正在为模拟游戏开发人类统计数据库,但无法确定某个 function。 The data about each person is stored as a string in a
humandict
list.每个人的数据以字符串形式存储在
humandict
列表中。 Every in-game year the ageup()
func should be called, and change each strings data value.每个游戏年份都应该调用
ageup()
函数,并更改每个字符串的数据值。
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.我调用
.split()
方法是为了将字符串中的这些不同数字划分为一个列表,并将int()
应用于每个列表项以便在数学中使用它们。 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 ): ageup()
function 应该访问每个humandict
项目并将年龄值更改为 1。这是我目前使用的代码(不能按预期工作):
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:代码成功运行一次,下次调用 function 时出现以下错误:
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.我根本不明白问题出在哪里,可能是由于错误的 ID 分配或其他原因。 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).
这种方式代码也很有效(因为数据操作较少)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.