[英]python for loops being started at 1st element no 0th element
I am writing a simple text-based RPG battle simulator using Python (running on PyCharm).我正在使用 Python(在 PyCharm 上运行)编写一个简单的基于文本的 RPG 战斗模拟器。 I created a class called Person which has initialization parameters as follows:
我创建了一个名为 Person 的 class,其初始化参数如下:
def __init__(self, name, HP, MP, ATK, DEF, magic, items):
self.name = name
self.HP = HP
etc...
this class gets instantiated 3 times in main
for 3 unique players ( player1, player2, player3
).这个 class
main
为 3 个独特的玩家( player1, player2, player3
)实例化 3 次。 I also have a function get_stats(self)
which does我也有一个 function
get_stats(self)
print(self.name + ", HP: " + self.HP + ", MP: " + self.MP)
but when I run in main
但是当我在
main
中运行时
for player in players:
player.get_stats()
where players = {player1, player2, player3}
, I get the output (note that the MP/HP values are arbitrary):其中
players = {player1, player2, player3}
,我得到 output (注意 MP/HP 值是任意的):
name2, HP: 200, MP: 200
name3, HP: 300, MP: 300
name1, HP: 100, MP: 100
and if players = {player0, player1, player2, player3}
, I get the output:如果
players = {player0, player1, player2, player3}
,我得到 output:
name2, HP: 200, MP: 200
name3, HP: 300, MP: 300
name0, HP: 400, MP: 400
name1, HP: 100, MP: 100
why does this happen and how can I fix it?为什么会发生这种情况,我该如何解决?
{}
creates a set
in python, which are not ordered: the elements are not stored in the way they are entered. {}
在 python 中创建一个未排序的set
:元素未按输入方式存储。
You need a list, which can be created as:您需要一个列表,可以创建为:
players = [player1, player2, player3]
or a tuple:或元组:
players = (player1, player2, player3)
You are using the {}
syntax that is meant for set
s in Python.您正在使用用于 Python 中的
set
的{}
语法。 Sets do not have an order, and will yield their members at random when used in a for
statement.集合没有顺序,在
for
语句中使用时会随机产生其成员。
Simply be consistent and use (Player0, ...)
to denote a tuple, or [Player0, ...]
to denote a list - both of these types are "sequences", which have a well defined order.只需保持一致并使用
(Player0, ...)
表示元组,或[Player0, ...]
表示列表 - 这两种类型都是“序列”,具有明确定义的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.