如何做一个好朋友!Python中的布尔变量say 0
我打电话给winOrLose 1或0。我试过了!python中的myVariable,它表示“无效语法错误” 那很好。如果我这样做:如何做一个好朋友!Python中的布尔变量say 0,python,boolean,Python,Boolean,我打电话给winOrLose 1或0。我试过了!python中的myVariable,它表示“无效语法错误” 那很好。如果我这样做: newFileWriter.writerow([rightPlayersID, rightPlayerCharacters, not winOrLose]) not winOrLose返回“False”而不是0。。。即使winOrLose是1。我该如何优雅地做到这一点?我认为数据应该是“0”而不是“false”,因为我用它来进行机器学习。谢谢。使用int
newFileWriter.writerow([rightPlayersID, rightPlayerCharacters, not winOrLose])
not winOrLose返回“False”而不是0。。。即使winOrLose是1。我该如何优雅地做到这一点?我认为数据应该是“0”而不是“false”,因为我用它来进行机器学习。谢谢。使用int()函数将其转换为整数
把你的答案转换成一个整数。 通过以下方式之一:
int(not winorlose)
或通过:
if not winorlose == True:
winorlose = 1
else:
winorlose = 0
我相信python不支持!运算符。调用变量,例如
won
。如果您赢了,请将其设置为True
,否则设置为False
。那么您的代码将如下所示
if won:
print ("I won!")
else:
print ("I lost")
要对其求反,请使用not
运算符。所以
if not won:
print ("I lost!")
比
wonorlost
可读性强得多。至于将其设置为整数,如果为0,则可以使用1
您可以针对您的条件:
winOrLose = 1 if (battles[idx]['outcome'] == 'victory') else 0
然后,在编写时,按原样使用代码:
newFileWriter.writerow([rightPlayersID, rightPlayerCharacters, not winOrLose])
但是,使用此类条件语句的警告是,除“victory”之外的任何其他输入都将给出0(代码不言而喻)
至于逻辑运算符
代码>。在Python中,逻辑运算符如下:和
、或
和非
。因此,not
等同于。您可以使用简单代数:
1 - 0 == 1
1 - 1 == 0
因此,lambda x:1-x
是您的求反函数。您可以使用(如果winOrLose为1,则为0,否则为1)
。您的解决方案更加优雅!
newFileWriter.writerow([rightPlayersID, rightPlayerCharacters, not winOrLose])
1 - 0 == 1
1 - 1 == 0