2017-10-28 45 views
3

我知道使用相同的變量名是不好的做法。錯誤,當我在列表理解中使用相同的變量名稱

我只想知道爲什麼會發生這種技術上的問題。

In [1]: a=[1,2,3] 

In [2]: b=[4,5,6] 

In [3]: [a for a in a] 
Out[3]: [1, 2, 3] 

In [4]: a 
Out[4]: [1, 2, 3] 

In [5]: [(a,c) for a in a for c in b] 
Out[5]: [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)] 

In [6]: [(a,b) for a in a for b in b] 
--------------------------------------------------------------------------- 
UnboundLocalError       Traceback (most recent call last) 
<ipython-input-6-bac0ec331d24> in <module>() 
----> 1 [(a,b) for a in a for b in b] 

<ipython-input-6-bac0ec331d24> in <listcomp>(.0) 
----> 1 [(a,b) for a in a for b in b] 

UnboundLocalError: local variable 'b' referenced before assignment 

回答

相關問題