2017-07-20 407 views
0

我在下面的Python代碼錯誤在Python代碼

a=[1,2,3,4,5,6,7,8,9] 
c,d=divmod(len(a),2) 
i=iter(a).next 
print ''.join('%s\t%s\n' % (i(),i()) 
for i in xrange(c))\ 
+ ('%s\t\n' % (i()) if b==1 
    else '') 

我需要打印輸出得到錯誤是

1 2 
3 4 
5 

我得到錯誤:

Traceback (most recent call last): 
    File "dhsgj.py", line 5, in <module> 
    for i in xrange(c))\ 
    File "dhsgj.py", line 5, in <genexpr> 
    for i in xrange(c))\ 
TypeError: 'int' object is not callable 
+0

你期望'我()'做什麼? – user3080953

+0

@ user3080953它調用'next'函數。它在第三行中聲明。 –

+0

第5行,您將覆蓋第三行的「i」 –

回答

0

你做不需要拆分數組,嘗試一次迭代兩個項目。

我已更新您的代碼,使其更容易遵循。這應該工作:

a=[1,2,3,4,5,6,7,8,9] 
iterator = iter(a) 
for first in iterator: 
    try: 
     second = next(iterator) 
    except StopIteration: 
     print first 
    else: 
     print('%s\t%s\n' % (first, second)) 
+0

謝謝你的支持 –