【发布时间】:2017-07-04 11:58:57
【问题描述】:
我正在尝试对列表进行排序。我如何才能打印或迭代每个列表中的第一个和最后一个元素?下面的非工作代码:
from numpy import *
xs=[[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]]
for i in xs:
for j in xs[i]:
print(xs[1],xs[-1])
如果需要,追溯错误:
runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')
Traceback (most recent call last):
File "<ipython-input-14-8a28382c7f81>", line 1, in <module>
runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')
File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
execfile(filename, namespace)
File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/Alex/untitled9.py", line 13, in <module>
for j in xs[i]:
TypeError: list indices must be integers or slices, not list
【问题讨论】:
-
for i in xs:print(i[1], i[-1])应该可以正常工作。 -
其实应该是
for i in xs:print(i[0], i[-1]) -
如果我想同时为多个列表做同样的事情?
-
这能回答你的问题吗? Iterating through list of list in Python