试图在功能shuffle_deck中随机播放卡片组列表,但是当我在create_deck中对其进行编辑时,它并没有保存更改。我以为将其附加在函数内部会更改全局字段中的列表,而不仅是函数内部,而且可能是错误的。如何获取shuffle_deck函数从create_deck而不是空的甲板上看到附加的套牌?
import random
deck=[]
def Create_Deck():
suits = ('Spades','Hearts','Clubs','Diamonds')
for suit in suits:
for card in range(1,14):
if card == 1:
card = 'Ace'
elif card == 11:
card = 'Jack'
elif card == 12:
card = 'Queen'
elif card == 13:
card = 'King'
deck.append(str(card) + ' of ' + suit)
print(deck)
def shuffle_deck():
random.shuffle(deck)
print(deck)`
print(shuffle_deck())
print(Create_Deck())
我希望能够在shuffle_deck中打印(甲板),并且它是create_deck中甲板的随机版本。
答案 0 :(得分:1)
您调用函数的顺序是错误的。调用deck
时[]
的值是一个空列表shuffle_deck
。只需在Create_deck
之前致电shuffle_deck
。
print(Create_Deck())
print(shuffle_deck())
有关global
的使用方式和地点的一些其他信息:
如果全局变量指向一个{strong>可变的python对象,例如list
,则无需使用global
声明。但是,不能将赋值语句与变量一起使用。在不更改变量引用的情况下,无需更改global
声明即可对对象进行修改。
对于引用不可变数据的变量,赋值语句本质上会更改变量的引用,当发生这种情况时,python会创建该变量的本地副本,并且不会触及全局数据。要直接修改全局变量,请在函数开始时将其声明为global
。
x = 10
def change_x():
x = 20 # this is a local `x`
print(f'After changing: x = {x}')
print(f'Before function call: x = {x}')
change_x()
print(f'After function call: x = {x}')
输出:
Before function call: x = 10
After changing: x = 20
After function call: x = 10
现在,让我们使用global
声明
x = 10
def change_x():
global x
x = 20
print(f'After changing: x = {x}')
print(f'Before function call: x = {x}')
change_x()
print(f'After function call: x = {x}')
输出:
Before function call: x = 10
After changing: x = 20
After function call: x = 20
对于可变类型,不需要global
声明。
x = [1, 2, 3]
def change_x():
x.append(4)
print(f'After changing: x = {x}')
print(f'Before function call: x = {x}')
change_x()
print(f'After function call: x = {x}')
输出:
Before function call: x = [1, 2, 3]
After changing: x = [1, 2, 3, 4]
After function call: x = [1, 2, 3, 4]
但是,为其分配其他值将不起作用。
x = [1, 2, 3]
def change_x():
x = [10, 20, 30]
print(f'After changing: x = {x}')
print(f'Before function call: x = {x}')
change_x()
print(f'After function call: x = {x}')
输出:
Before function call: x = [1, 2, 3]
After changing: x = [10, 20, 30]
After function call: x = [1, 2, 3]