[英]Python: why does this code fail? assigning variable to list of itself in for loop
a = 'hello'
b = None
c = None
for x in [a, b, c]:
if isinstance(x, (basestring, dict, int, float)) or x is None:
x = [x]
a
返回“你好”,但预期['你好']。 但是,这有效:
a = 'hello'
a = [a]
a
返回['你好']
要实现这一点,首先你要了解你有两个不同的结果,a和x(对于每个元素),以及列表[a,b,c]的引用,仅在for循环中使用,而且永远不会更多。
为了实现目标,您可以这样做:
a = 'hello'
b = None
c = None
lst = [a, b, c] #here I create a reference for a list containing the three references above
for i,x in enumerate(lst):
if isinstance(x, (str,dict, int, float)) or x is None: #here I used str instead basestring
lst[i] = [x]
print(lst[0]) #here I print the reference inside the list, that's why the value is now showed modified
['你好']
但正如我所说,如果你打印(a)它会再次显示:
'你好'#here我打印了变量a的值,没有修改
因为你从来没有做过任何事。
看一下这个问题,了解更多关于引用的信息如何通过引用传递变量?
让我们一次完成这一行;
a = 'hello' # assigns 'hello' to a.
b = None # etc...
c = None
for x in [a, b, c]: # Creates list from the values in 'a' 'b' and 'c', then iterates over them.
# This if statement is always True. x is always either a string, or None.
if isinstance(x, (basestring, dict, int, float)) or x is None:
x = [x] # On the first iteration, sets variable to the expected ['hello']
# After that though - it replaces it with [None]
a # = 'hello' - you have not assigned anything to the variable except on the first line.
唯一设置为['hello']
变量是x
,用None
快速覆盖。 如果您将if检查更改为exclude or x is None
并分配给a
而不是x
,则可以获得所需的结果。
值得注意的是,当你启动for循环时会创建列表[a, b, c]
。 改变a
b
或c
在for循环将没有任何效果-这样的名单已经产生。
其他答案很棒。 我认为,概括来说,list元素是不可变的/可散列的,因此for循环返回一个副本,而不是对原始对象的引用。 我应该发现这一点,但教我编码太长时间不睡觉!
我最终使用了这个:
def lst(x):
if isinstance(x, (basestring, dict, int, float)) or x is None:
x = [x]
return x
[a, b, c] = map(lst, [a, b, c])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.