【发布时间】:2015-08-24 02:58:22
【问题描述】:
这里的初学者词典问题。我有这个代码:
import random
abilities = {
'Spell': '''fireball missile dread curse fear teleport shield
cure heal blast reveal fade taunt reveal haste shock'''.split(),
'Weapon': '''axe sword mace club longbow shortbow crossbow greatsword
greataxe dagger shortsword longsword staff claw'''.split(),
'Skill': '''jump slash parry dodge block smash grab jab evade stab
crush charm lure lift throw grapple punch'''.split(),
'Monster': '''goblin troll ogre ninja pirate knight warlock witch
mage lich ooze gargoyle bandit thief wizard swordmaster'''.split()}
def getAbility(abilityDict):
#get ability key
abilityKey = random.choice(list(abilityDict.keys()))
#get random value from ability key
abilityValue = random.randint(0, len(abilityDict[abilityKey]) -1)
return [abilityDict[abilityKey][abilityValue], abilityKey]
ability, abilityKey = getAbility(abilities)
print abilityKey, ability
当我调用 print 函数时,它会评估为像“Monster ooze”或“Weapon Sword”这样的字符串
但是,当我在函数中更改这一行时:
return [abilityDict[abilityKey][abilityValue], abilityKey]
到这里:
return [abilityDict[abilityKey][abilityValue]]
并改变这个:
ability, abilityKey = getAbility(abilities)
print abilityKey, ability
到这里:
ability = getAbility(abilities)
print ability
然后 print 函数从列表格式的随机键中计算出一个随机值,因此 ['bandit'] 或 ['axe']
我的问题是: 为什么 return [abilityDict[abilityKey][abilityValue],abilityKey] 返回一个字符串,而 return [abilityDict[abilityKey][abilityValue]] 返回一个列表?
我只需要知道为什么,因为仅仅记住它并不能真正帮助我掌握 Python 字典的概念。
感谢您提供的任何帮助。
【问题讨论】:
标签: python-2.7