英文:
Check if array contains object with certain string
问题
我有一个非常简单的数组,像这样:
players = []
我想要检查用户名是否存在于数组中,如果存在,就不应该添加用户。我认为遍历数组可能不是最明智的方法,因为每次运行可能会太大。
我也想到可以使用字典,但以前从未这样做过,所以不知道是否能解决我的问题。
我的Player类看起来像这样:
class Player:
def __eq__(self, other):
return self._username == other._username
def __init__(self, x, y, name, sprite):
# 更多内容
主要问题是,我需要从两个不同的函数访问这个数组,这就是为什么我可能不能使用 if character in players
进行检查的原因。
查看完整的代码:
这是我将角色添加到数组的地方:
@commands.command(name='join')
async def join(self, ctx: commands.Context):
character = Player(random.randint(100, 400), 210, ctx.author.display_name, random.choice(["blue", "red"]))
if character not in players:
await ctx.send(f'You are in, {ctx.author.name}!')
players.append(character)
else:
await ctx.send(f'You are already in, {ctx.author.name}!')
这是我想要检查名称是否已经存在于数组中的地方,所以它将打印 "can quest" 或 "can't quest, not ingame yet":
@commands.command(name='quest')
async def quest(self, ctx: commands.Context):
# 检查玩家是否加入游戏
print(players)
await ctx.send(f'{ctx.author.name} joined the quest!')
希望这些部分能对你有所帮助。
英文:
I have a pretty simple array like this:
players = []
I want to check if username is exists in the array, if so, then the user shouldn't be added. I don't think iterating through the array would be the smartest approach, because it might be to big to run this everytime.
I also thought it might be an idea to use a dict, but never did that before so I don't know if that would solve my problem.
My Player-Class looks like this:
class Player:
def __eq__(self, other):
return self._username == other._username
def __init__(self, x, y, name, sprite):
# more stuff
The main problem is, that I need to access this array from two different function, which is why I probably can't check with if character in players
Have a look at the full code:
This is where I add the character to my array:
@commands.command(name='join')
async def join(self, ctx: commands.Context):
character = Player(random.randint(100, 400), 210, ctx.author.display_name, random.choice(["blue", "red"]))
if character not in players:
await ctx.send(f'You are in, {ctx.author.name}!')
players.append(character)
else:
await ctx.send(f'You are already in, {ctx.author.name}!')
Here where I want to check if the name already exists in the array, so it will either print "can quest" or "can't quest, not ingame yet"
@commands.command(name='quest')
async def quest(self, ctx: commands.Context):
#check if player joined the game
print(players)
await ctx.send(f'{ctx.author.name} joined the quest!')
or similar?
答案1
得分: 2
你可以使用 any()
和一个推导表达式:
if any(player.username == "Fred" for player in players)
这段代码会遍历 players
列表中的每个项,检查玩家是否具有名字 "Fred"。
如果找到匹配项,它将停止迭代并返回 True。
如果找不到匹配项,它将返回 False。
英文:
You can use any()
and a comprehension expression:
if any(player.username == "Fred" for player in players)
This code will iterate over each item in the players
list, checking if that player has a name of "Fred".
If it finds a match, it will stop iterating and return True.
If it does not find a match, it will return False.
答案2
得分: 0
你建议使用字典。以下是如何实现的示例代码:
players = {}
# 这是如何添加一个玩家的方式
if user_name not in players:
players[user_name] = Player(user_name)
else:
print(f"{user_name} 已存在")
下面的代码展示了字典的样子:
{'Michelle': Player('Michelle'), 'Raul': Player('Raul')}
英文:
You suggested using a dictionary. Here is how you would do it:
players = {}
# This is how you add a player
if user_name not in players:
players[user_name] = Player(user_name)
else:
print(f"{user_name} already exists")
The code below shows what the dictionary would look like
{'Michelle': Player('Michelle'), 'Raul': Player('Raul')}
答案3
得分: 0
你可以使用字典来检查玩家数组中是否存在用户名,相比遍历数组,字典提供了更快的查找速度。
示例:
players = {}
# 添加玩家
username = "example"
if username not in players:
character = Player(username)
players[username] = character
print("玩家添加成功。")
else:
print("用户名已存在。")
# 检查用户名是否存在
username = "example"
if username in players:
print("用户名存在。")
else:
print("用户名不存在。")
在这段代码中,players
字典以用户名作为键,相应的 Player
对象作为值。在添加玩家时,它会检查用户名是否已存在于字典中。如果不存在,将创建一个新玩家并将其添加到字典中。如果已存在,则表示用户名已被占用,玩家不会被计算在内。
在检查用户名是否存在时,你可以使用 in
运算符来检查用户名是否是字典中的键。
英文:
You can use a dictionary instead of a list to check if a username exists in the players' array. Dictionaries provide faster lookup times compared to iterating through an array.
Example:
players = {}
# Adding players
username = "example"
if username not in players:
character = Player(username)
players[username] = character
print("Player added successfully.")
else:
print("Username already exists.")
# Checking if the username exists
username = "example"
if username in players:
print("Username exists.")
else:
print("Username does not exist.")
In this code, the players' dictionary uses the username as the key and the corresponding Player
object as the value. When adding a player, it checks if the username already exists in the dictionary. A new player is created and added to the dictionary if it doesn't exist. If it does exist, the username is already taken, and the player is not counted.
When checking if a username exists, you can use the in
operator to check if the username is a key in the dictionary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论