简体   繁体   English

Python:为什么这段代码失败了? 将变量分配给for循环中的自身列表

[英]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

returns 'hello', but expected ['hello']. 返回“你好”,但预期['你好']。 However, this works: 但是,这有效:

a = 'hello'
a = [a]
a

returns ['hello'] 返回['你好']

To achieve that, first you have to understand that you have two diferent refecerences, a and x (for each element), and the reference for the list [a,b,c], used only in the for loop, and never more. 要实现这一点,首先你要了解你有两个不同的结果,a和x(对于每个元素),以及列表[a,b,c]的引用,仅在for循环中使用,而且永远不会更多。

To achieve your goal, you could do this: 为了实现目标,您可以这样做:

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

['hello'] ['你好']

but as I said, if you do print(a) it will show again: 但正如我所说,如果你打印(a)它会再次显示:

'hello' #here i printed the value of the variable a, wich has no modification '你好'#here我打印了变量a的值,没有修改

because you never did anything with it. 因为你从来没有做过任何事。

Take a look at this question to understand a little more about references How do I pass a variable by reference? 看一下这个问题,了解更多关于引用的信息如何通过引用传递变量?

Lets work through this one line at a time; 让我们一次完成这一行;

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.

The only variable that is ever set to ['hello'] is x , which is quickly overwritten with None . 唯一设置为['hello']变量是x ,用None快速覆盖。 If you changed your if check to exclude or x is None and assigned to a instead of x you would get your desired result. 如果您将if检查更改为exclude or x is None并分配给a而不是x ,则可以获得所需的结果。

It's also worth noting that the list [a, b, c] is created when you start the for loop. 值得注意的是,当你启动for循环时会创建列表[a, b, c] Changing a b or c during the for loop will have no effect - the list has already been created. 改变a bc在for循环将没有任何效果-这样的名单已经产生。

Other answers are great. 其他答案很棒。 I think, to generalize, the list element is immutable/hashable so the for loop returns a copy, not a reference to the original object. 我认为,概括来说,list元素是不可变的/可散列的,因此for循环返回一个副本,而不是对原始对象的引用。 I should've spotted this, but teaches me for coding too long without sleep! 我应该发现这一点,但教我编码太长时间不睡觉!

I ended up using this: 我最终使用了这个:

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.

相关问题 为什么列表的此代码对于大型条目会失败? - Why does this code for a list fail for large entries? 为什么这个Python代码(使用自己的地图合成列表扩展)会使我的系统冻结? - Why does this Python code (compositing a list extension with a map of itself) make my system freeze up? Python:将列表中的每个项目创建为变量,并在 for 循环中为其赋值 - Python: Creating each item in a list as a variable and assigning a value to it in a for loop 为什么将列表切片分配给另一个变量会改变结果? - Why does assigning the list slice to another variable change the result? 为什么尽管存在无限循环,该Python服务还是会自行停止? - Why does this Python service stop by itself in spite of an infinite loop? 为python 3分配while循环中的列表 - Assigning to list in while loop for python 3 Python 是否在每个循环中为变量创建/分配值比在循环外创建/分配变量需要更多的内存/时间? - Python Does creating/assigning a value to a variable every loop take more memory/time than creating/assigning a variable outside the loop? 为什么此Python循环无法输出到下一个可用的excel行? - Why does this Python loop fail to output to the next available excel row? 为什么不为if块(位于for循环内)内的列表元素分配新值,则不会更改实际的列表本身? - Why doesn't assigning a new value to a list element inside an if block (which is inside a for loop) not change the actual list itself? 为什么For循环会产生可变列表长度 - Why does the For loop produce variable list length
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM