gpt4 book ai didi

Python如何更改列表中引用的变量

转载 作者:太空宇宙 更新时间:2023-11-04 10:48:14 24 4
gpt4 key购买 nike

import random
warrior = 'Warrior'
mage = 'Mage'
warlock = 'Warlock'
paladin = 'Paladin'
firstList = [warrior, mage, warlock, paladin]
print(firstList[0], firstList[1], firstList[2], firstList[3])
firstNumber = random.randint(0, 3)
firstList[firstNumber] = '*taken*'
print(firstList[0], firstList[1], firstList[2], firstList[3])
secondList = [paladin, warlock, mage, warrior]
print(secondList[0], secondList[1], secondList[2], secondList[3])

假设随机数选择 0我意识到第 9 行实际上只是将列表条目更改为“taken”,而不是将条目引用的“warrior”变量更改为“taken”。有什么办法吗?

请原谅魔兽世界的引用。

最佳答案

你想改用字典:

taken = {'warrior': False, 'mage': False, 'warlock': False, 'paladin': False}
names = {'warrior': 'Warrior', 'mage': 'Mage', 'warlock': 'Warlock', 'paladin': 'Paladin'}

或:

taken = dict.fromkeys(('warrior', 'mage', 'warlock', 'paladin'), False)
names = {character: character.capitalize() for character in taken}

然后选择一个随机字符:

from random import choice
picked = choice(list(names.keys()))
taken[picked] = True
print('Picked:', names[picked])

您真的不想使用单独的本地标识符来表示一组字符,这只会使事情复杂化。

关于Python如何更改列表中引用的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15810645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com