访问矩阵/列表中的索引或行
不使用numpy,我的问题与python中的for循环有关,因为它没有i = 0,i ++ ...
仅具有 <代码>对于我在列表中的
我需要
for i in list
# print(i.index)
# i.index being 0 at the first element of the list and
# ordered to len(list)-1 at the last element
我缺少的东西:
mat=[[1,0,1],
[1,1,1],
[1,0,1]]
dict1= []
dict2= []
n=len(mat[0])
for row in mat :
for j in range(n):
if row[j]==0:
dict1.append(mat.index(row))
dict2.append(j)
print(dict1)
print(dict2)
输出应该是[0,2]和[1,1],但是我得到了
[0,0]
[0,1]
我们如何解释这一点?
Without using numpy, my question is related to the for loop in Python, as it doesn't have for i=0, i++ ...
onlyfor i in list
I need
for i in list
# print(i.index)
# i.index being 0 at the first element of the list and
# ordered to len(list)-1 at the last element
There is something I am missing :
mat=[[1,0,1],
[1,1,1],
[1,0,1]]
dict1= []
dict2= []
n=len(mat[0])
for row in mat :
for j in range(n):
if row[j]==0:
dict1.append(mat.index(row))
dict2.append(j)
print(dict1)
print(dict2)
output should be [0,2] and [1,1] but instead I am getting
[0,0]
[0,1]
How do we explain this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
另一个可能性是
对i,v in Enumerate(my_list):print(i,v)
。i
值从0
到len(my_list) - 1
。函数枚举
具有关键字参数start
允许指定i
start(如上所述,此默认为0
) 。Another possibility is
for i,v in enumerate(my_list): print(i, v)
. Thei
value goes from0
tolen(my_list) - 1
. The functionenumerate
has keyword argumentstart
that allow to specify wherei
starts (as above this defaults to0
).使用
.index()
Use
.index()
使用.index()是可以的,只要列表没有双输入,索引返回第一次出现项目的索引。
For循环可以在某些范围内通过索引 i 迭代:
Using .index() is okay, as long as the list does not have double entries, because index returns the index of the first occurrence of an item.
The for loop can iterate over an index i in some range as follows: