python - 在引用原始变量后编辑它
问题描述
check1 = False
check2 = False
if x == y:
sending = check1
elif x == z:
sending = check2
if something is True:
if sending is False: #actually checks if check1 or check2 is False
do_stuff()
sending = True #1 - want to change the actual variable ( check1 or check2 )
await ask_for_confirmation()
else:
return
我参考check1
或check2
依赖于其他一些变量,之后如果选择的变量是False
ido_stuff()
和ask_for_confirmation()
,并且想要将特定选择的变量更改为True
它不会do_stuff()
再次(确认再次运行整个事情)。
我知道我可以像这样再次检查变量:
check1 = False
check2 = False
if x == y:
sending = check1
elif x == z:
sending = check2
if something is True:
if sending is False:
do_stuff()
if x == y:
check1 = True
elif x == z:
check2 = True
await ask_for_confirmation()
else:
return
但这似乎有很多不必要的代码,我觉得有更好的方法来做到这一点。有没有办法可以用参考改变原始变量?(见上面代码中的#1)
解决方案
您遇到的问题是,当您重新分配时sending
,您只是将其指向不同的值,而不是修改它先前指向的值。
您要做的是将您的两个check
值放入一个可变容器中,例如一个列表,然后修改该列表。
checks = [False, False]
if x == y:
sending = 0
elif x == z:
sending = 1
# else:
# sending = ???
if something:
if checks[sending]:
return
do_stuff()
checks[sending] = True
await ask_for_confirmation()
或将每个放入自己的可变容器中(您仍然需要为容器下标以访问或修改它包含的值):
check1 = [False]
check2 = [False]
if x == y:
sending = check1
elif x == z:
sending = check2
# else:
# sending = ???
if something:
if sending[0]:
return
do_stuff()
sending[0] = True
await ask_for_confirmation()
推荐阅读
- memory - Chisel - 内存初始化
- java - tomcat启动时的ContextLoaderListener异常
- python-3.x - Python Dash数据表:行选择不起作用
- laravel-nova - Laravel Nova 搜索字幕
- regex - 正则表达式 - 如何在不同的行中交换两个表达式?
- excel - VBA EXCEL .AutoFilter 逻辑
- laravel - 如何在刀片文件中使用 vue 组件,如单选按钮?
- swiftui - 如何在不中断删除的情况下在 SwiftUI 中实现 TextField 列表
- python - 设置单个轴对象(XAxis 或 YAxis)的限制
- javascript - 适用于 repl.it 不适用 freeCodeCamp - JavaScript 算法和数据结构项目:罗马数字转换器