我正在尝试对列表进行排序。我如何打印或迭代每个列表中的第一个和最后一个元素?下面的非工作代码:
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])
Run Code Online (Sandbox Code Playgroud)
如果需要则回溯错误:
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
Run Code Online (Sandbox Code Playgroud)
评论里已经给你答案了。但要了解为什么您的代码在当前状态下不起作用,请看一下:
>>> xs = [[1.,2.,3.], [4.,5.,6.], [7.,8.,9.]]
>>> for i in xs:
... print(i)
...
[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
[7.0, 8.0, 9.0]
Run Code Online (Sandbox Code Playgroud)
循环for迭代elements,而不是索引。这里的变量i可能令人困惑。无论如何,在循环内部,i每次迭代都会包含一个子列表。这里的操作也是xs[i]无效的——你只能提供整数作为 python 列表的索引。
如果你想获取每个子列表的第一个和最后一个元素,你所要做的就是打印出i[0]和i[-1]。
在相关说明中,您可以使用以下函数迭代索引range:
for i in range(len(xs)):
print(xs[i][0], xs[i][-1])
Run Code Online (Sandbox Code Playgroud)
但不建议这样做,因为直接迭代元素会更有效,特别是对于这种用例。
enumerate如果您同时需要,也可以使用:
for c, i in enumerate(xs):
print(i[0], xs[c][-1]) # both work here
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6140 次 |
| 最近记录: |