当两个变量放在一个if语句中时,它意味着什么:variable[variable2]?

2024-10-16 20:39:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,从书中学习似乎无法在书中或谷歌上的任何地方找到我想要的答案。也许我只是没有把我的问题写对

书中有一个简单的井字游戏。if语句是这样写的

if theBoard[move] == ' ':

theBoard是一个字典,move是一个输入。我想知道当两个变量像这样坐在一起,一个在括号内时,这意味着什么


Tags: 答案游戏moveif字典地方语句括号
3条回答

对于dictionary,它意味着从dictionary中获取元素

dictionary = {
  'item_1': '...',
  'item_2': '1',
  'item_3': 2,
}

dictionary['item_1'] # you can get item_1 from dictionary like this

# or this
item_name = 'item_1'
dictionary[item_name]

对于列表,可以使用索引获取其中的项存储

  obj = object()
  li = [1, '2', obj, ]
  
  # slicing operation in list
  li[0]   # get the 1st item.
  li[-1]  # get the last item.
  li[1:3] # get item from index 1 to 3 not include index 1.
  li[:]   # get all item. it can use to copy the list.

你需要访问字典才能使用它,对吗?方括号表示move的值与字典中的另一个值相关联。代码的意思是,如果字典中与字典中move值关联的值是一个空格,那么执行一些代码。在你的余生中,你会看到这个方括号符号,所以我真的会钻这个

看起来你在看this tic-tac-toe game

正如您所提到的,theBoard是一个字典,这里是它的初始条件:

theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
            '4': ' ' , '5': ' ' , '6': ' ' ,
            '1': ' ' , '2': ' ' , '3': ' ' }

In Python dictionaries have 'keys' and 'values'(点击链接了解更多信息)。在这种情况下,键是数字1-9,并且至少在开始时,它们都等于' '

[key]添加到字典的名称后,将提取该键的值

例如:

# define the dict
dictionary = {'key1':'value1', 'key2':'value2'} 
# extract value2
dictionary['key2']

在您的示例中move是键,用于检查值是否为' '

如上所述,类似的语法贯穿整个Python。值得回顾一下data structures documentation以巩固概念

相关问题 更多 >