Python字典在将它们用作函数参数时

huangapple go评论100阅读模式
英文:

Python dictionaries when using them as function arguments

问题

I am probably not using dictionaries right but anyway, here is what I was trying to do:

我可能没有正确使用字典,但无论如何,这是我试图做的事情:

  1. Set up a starting dictionary. This would be used as an empty template.
    1)建立一个起始字典。这将用作空模板。

  2. pass the dictionary to a function. In the function it will be assigned a new variable name so I can do things to it.
    2)将字典传递给一个函数。在函数中,它将被分配一个新的变量名,以便我可以对它进行操作。

  3. work on the dictionary by adding items to it.
    3)通过向字典添加项目来操作字典。

  4. return the dictionary to some other variable in the main code.
    4)将字典返回给主代码中的其他变量。

  5. repeat the above for another variable in the main code. each time taking in that template dictionary and doing things to it.
    5)对主代码中的另一个变量重复上述步骤。每次使用该模板字典并对其进行操作。

But what seems to happen is that the "starting" dictionary is updated as well so when I pass it for the second time, its full of information I don't want.

但似乎发生的情况是,“起始”字典也被更新了,所以当我第二次传递它时,它充满了我不想要的信息。

Here is a minimum example:

这是一个最小的示例:

startDeck = {
  "deckSize": 0,
  "score": 0,
  "blackjack": False,
}

def playBlackjack(deck):
  userDeck = dealCards(cards=deck, count=2)
  compDeck = dealCards(cards=deck, count=1)

def dealCards(cards, count):
  score = cards["score"]
  deckSize = cards["deckSize"]
  
  for n in range(count):
    newCard = {}
    deckSize += 1
    score += 1
    cardNo = "card" + str(deckSize)

    newCard["card"] = "hearts"
    newCard["value"] = 10
    newCard["suit"] = "clubs"
    cards[cardNo] = newCard

  cards["score"] = score
  cards["deckSize"] = deckSize

  return cards

playBlackjack(startDeck)

我认为这应该可以工作。我知道这可能不会太有意义,也许我不应该使用字典,但我在使用字典方面遇到了困难,想尝试一下以更好地理解。但基本上这里发生的情况是所有的字典,无论是顶部的"startDeck"(我认为它应该是全局的,因此可以供任何函数使用,但Python一直告诉我它看不见它?)还是我认为只在函数运行时存在的字典,最终都被填充了完全相同的信息。我不明白为什么会这样。

英文:

I am probably not using dictionaries right but anyway, here is what I was trying to do:

  1. Set up a starting dictionary. This would be used as an empty template.
  2. pass the dictionary to a function. In the function it will be assigned a new variable name so I can do things to it.
  3. work on the dictionary by adding items to it.
  4. return the dictionary to some other variable in the main code.
  5. repeat the above for another variable in the main code. each time taking in that template dictionary and doing things to it.

But what seems to happen is that the "starting" dictionary is updated as well so when I pass it for the second time, its full of information I don't want.

Here is a minimum example:

startDeck = {
  "deckSize":0,
  "score":0,
  "blackjack":False,
}


def playBlackjack(deck):
  userDeck = dealCards(cards= deck,count=2)
  compDeck = dealCards(cards= deck,count=1)

def dealCards(cards,count):
  
  score = cards["score"]
  deckSize = cards["deckSize"]
  
  for n in range(count):
    newCard = {}
    deckSize+=1
    score+=1
    cardNo = "card" + str(deckSize)

    newCard["card"] = "hearts"
    newCard["value"] = 10
    newCard["suit"] = "clubs"
    cards[cardNo]=newCard

  cards["score"]=score
  cards["deckSize"]=deckSize

  return cards


playBlackjack(startDeck)

I think that should work. I know it probably won't make much sense and maybe I should not be using dictionaries, but I did struggle with them and wanted to have a go with them to understand more.

But essentially what is happening here is all the dictionaries, whether its that "startDeck" one at the top (which I thought would be global and thus available to any function but I keep getting told by python that it can't see it?) or the dictionaries that I thought would only exist while the function runs, all end up filled with exactly the same information. And I don't understand why.

答案1

得分: 1

这是因为字典被传递为引用。您可以通过搜索“引用 vs 值类型”来了解更多信息,有很多关于这个主题的资源。

这是一个重要的编程概念,了解它对于知道您正在操作的对象非常重要(尤其是在使用Python时,它会执行某些操作,而其他语言可能会报错)。当明智地使用时,它是一个强大的工具。

简而言之,针对您的问题,Python 在函数 playBlackJack 中不会创建一个新的对象,因为字典属于引用类型。

要获得字典的副本,您可以使用以下方式:

from copy import deepcopy

def playBlackjack(initial_deck):
  deck = deepcopy(initial_deck)
  userDeck = dealCards(cards=deck, count=2)
  compDeck = dealCards(cards=deck, count=1)
英文:

This is because the dictionary is passed as a reference. You can learn more by Googling "Reference vs value types", there are plenty of resources about the topic.
It's a basic programming concept which is important to understand in order to be aware of what object you're manipulating (especially with Python as it will do stuff, where other languages might complain). And it's a powerful tool when used wisely.

To sum up your issue quickly, Python doesn't create a new object in your function playBlackJack, because dictionaries are part of reference types.

To have a copy of the dictionary, you can have:

from copy import deepcopy

def playBlackjack(initial_deck):
  deck = deecopy(initial_deck)
  userDeck = dealCards(cards=deck,count=2)
  compDeck = dealCards(cards=deck,count=1)

huangapple
  • 本文由 发表于 2023年6月27日 20:46:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76565018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定