索引函数在一个简单的嵌套for循环中没有

时间:2015-09-25 02:10:27

标签: python python-3.x

所以这是我正在使用的非常基本的代码,它是一个以元组元组的形式获取网格的函数。在循环中,我试图使我的行和q为网格的列。

def myfunc(grid):  
    for i in (grid): 
        for q in i: 
            print("i.index(q): ", i.index(q), " grid.index(i)", grid.index(i))

    return True

myfunc(((1, 0, 0, 1, 0),
        (0, 1, 0, 0, 0),
        (0, 0, 1, 0, 1),
        (1, 0, 0, 0, 0),
        (0, 0, 1, 0, 0)))

这是我得到的:

i.index(q):  0  grid.index(i) 0
i.index(q):  1  grid.index(i) 0
i.index(q):  1  grid.index(i) 0
i.index(q):  0  grid.index(i) 0
i.index(q):  1  grid.index(i) 0
i.index(q):  0  grid.index(i) 1
i.index(q):  1  grid.index(i) 1
i.index(q):  0  grid.index(i) 1
i.index(q):  0  grid.index(i) 1
i.index(q):  0  grid.index(i) 1
i.index(q):  0  grid.index(i) 2
i.index(q):  0  grid.index(i) 2

等等。

我期待并希望获得i.index(q)的0,1,2,4,5 ......,我没有正确使用此功能吗?这似乎很奇怪,因为grid.index(i)工作正常,当我在for q in i:循环中打印q时,我得到了正确的值。

任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

您完美地使用它们。但他们并不是你想要使用的东西。

#!/bin/bash
line=$(head -n 1 /etc/hosts | awk '{printf "%s %s.localdomain %s", $1, $2, $2}')
sed -e "1 s/^.*$/${line}/g" /etc/hosts > hosts
# with sed -i, it actually performs a rename of /etc/hosts, but docker does not
# allow that, so we have to use a temp file and copy it to overwrite /etc/hosts
cp hosts /etc/hosts
rm hosts

答案 1 :(得分:0)

tuple.index返回给定元素的第一次出现的索引:

In [1]: tuple.index?
Docstring:
T.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
Type:      method_descriptor

为了迭代元素及其索引,您应该使用enumerate函数:

In [2]: def myfunc(grid):
   ...:     for i, row in enumerate(grid):
   ...:         for j, elem in enumerate(row):
   ...:             print('Row #{}, elem #{}, value: {}'.format(i, j, elem))

In [3]: myfunc(((1, 0, 0, 1, 0),
   ...:         (0, 1, 0, 0, 0),
   ...:         (0, 0, 1, 0, 1),
   ...:         (1, 0, 0, 0, 0),
   ...:         (0, 0, 1, 0, 0)))
Row #0, elem #0, value: 1
Row #0, elem #1, value: 0
Row #0, elem #2, value: 0
Row #0, elem #3, value: 1
Row #0, elem #4, value: 0
Row #1, elem #0, value: 0
Row #1, elem #1, value: 1
Row #1, elem #2, value: 0
Row #1, elem #3, value: 0
Row #1, elem #4, value: 0
Row #2, elem #0, value: 0
Row #2, elem #1, value: 0
Row #2, elem #2, value: 1
Row #2, elem #3, value: 0
Row #2, elem #4, value: 1
Row #3, elem #0, value: 1
Row #3, elem #1, value: 0
Row #3, elem #2, value: 0
Row #3, elem #3, value: 0
Row #3, elem #4, value: 0
Row #4, elem #0, value: 0
Row #4, elem #1, value: 0
Row #4, elem #2, value: 1
Row #4, elem #3, value: 0
Row #4, elem #4, value: 0