英文:
how to use enumerate() to change a value in a nested list
问题
以下是翻译好的内容:
我有一个来自geotiff文件的二维数组。请看下面的示例数组:
example_array = [[ 0, 1, 1, 0, 0, 0, 0],
[ 2, 1, 1, 2, 0, 0, 0],
[ 0, 3, 1, 1, 3, 0, 0],
[ 4, 1, 1, 4, 0, 0, 0],
[ 0, 5, 1, 1, 5, 0, 0],
[ 0, 1, 1, 0, 0, 0, 0]]
我正在尝试编写一个程序,将每个嵌套列表中第一个大于1的数字更改为'值+100'。
在他人的帮助下,看下面的工作代码片段:
for i, sub_list in enumerate(example_array[1:], start= 1):
for j, entry in enumerate(sub_list[1:][1:1], start = 1):
if entry > 1 and j != 1 and j != len(sub_list):
example_array[i][j] += 100
print(example_array)
上述代码生成了下面的不正确示例数组,其中没有值发生更改:
incorrect_example_array = [[ 0, 1, 1, 0, 0, 0, 0],
[ 2, 1, 1, 2, 0, 0, 0],
[ 0, 3, 1, 1, 3, 0, 0],
[ 4, 1, 1, 4, 0, 0, 0],
[ 0, 5, 1, 1, 5, 0, 0],
[ 0, 1, 1, 0, 0, 0, 0]]
我想创建以下正确的示例数组:
correct_example_array = [[ 0, 1, 1, 0, 0, 0, 0],
[ 102, 1, 1, 2, 0, 0, 0],
[ 0, 103, 1, 1, 3, 0, 0],
[ 104, 1, 1, 4, 0, 0, 0],
[ 0, 105, 1, 1, 5, 0, 0],
[ 0, 1, 1, 0, 0, 0, 0]]
英文:
I have a 2D array from a geotiff file. See the example array below:
example_array = [[ 0, 1, 1, 0, 0, 0, 0],
[ 2, 1, 1, 2, 0, 0, 0],
[ 0, 3, 1, 1, 3, 0, 0],
[ 4, 1, 1, 4, 0, 0, 0],
[ 0, 5, 1, 1, 5, 0, 0],
[ 0, 1, 1, 0, 0, 0, 0]]
I am attempting to write a program that will change the first number greater than 1 in each nested list to the 'value + 100'.
With the help of others see the below working code snippet:
for i, sub_list in enumerate(example_array[1:], start= 1):
for j, entry in enumerate(sub_list[1:][1:1], start = 1):
if entry > 1 and j != 1 and j != len(sub_list):
example_array[i][j] += 100
print(example_array)
The above code produces the below incorrect example array where none of the values are changing:
incorrect_example_array = [[ 0, 1, 1, 0, 0, 0, 0],
[ 2, 1, 1, 2, 0, 0, 0],
[ 0, 3, 1, 1, 3, 0, 0],
[ 4, 1, 1, 4, 0, 0, 0],
[ 0, 5, 1, 1, 5, 0, 0],
[ 0, 1, 1, 0, 0, 0, 0]]
I would like to create the following correct example array
correct_example_array = [[ 0, 1, 1, 0, 0, 0, 0],
[ 102, 1, 1, 2, 0, 0, 0],
[ 0, 103, 1, 1, 3, 0, 0],
[ 104, 1, 1, 4, 0, 0, 0],
[ 0, 105, 1, 1, 5, 0, 0],
[ 0, 1, 1, 0, 0, 0, 0]]
答案1
得分: 0
外循环不需要索引;不需要使用enumerate
。可以在找到匹配项后立即中断内循环。对内部索引执行任何检查都是不必要的。
for l in example_array:
for x in l:
if x > 1:
l[i] += 100
break
英文:
The outer loop does not need the index; enumerate
is not needed. You can break the inner loop as soon as a match is found. There is no need to perform any checks on the inner index either.
for l in example_array:
for i, x in enumerate(l):
if x > 1:
l[i] += 100
break
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论