访问矩阵/列表中的索引或行

发布于 2025-01-26 13:07:20 字数 650 浏览 2 评论 0原文

不使用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++ ...

only
for 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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

独木成林 2025-02-02 13:07:20

另一个可能性是对i,v in Enumerate(my_list):print(i,v)i值从0len(my_list) - 1。函数枚举具有关键字参数start允许指定i start(如上所述,此默认为0) 。

Another possibility is for i,v in enumerate(my_list): print(i, v). The i value goes from 0 to len(my_list) - 1. The functionenumerate has keyword argument start that allow to specify where i starts (as above this defaults to 0).

阿楠 2025-02-02 13:07:20

使用.index()

l=[1,2,3]
for i in l:
    print(i,l.index(i))

1 0
2 1
3 2

Use .index()

l=[1,2,3]
for i in l:
    print(i,l.index(i))

1 0
2 1
3 2
爱你是孤单的心事 2025-02-02 13:07:20

使用.index()是可以的,只要列表没有双输入,索引返回第一次出现项目的索引。

For循环可以在某些范围内通过索引 i 迭代:

l=[1,2,3,5,6,7,3,1,89,2,77]
for i in range(0,len(l)):
    print(l[i], 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:

l=[1,2,3,5,6,7,3,1,89,2,77]
for i in range(0,len(l)):
    print(l[i], i)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文