循环遍历python数组,将特定值设置为指定列
我尝试了很多东西,但仍然坚持。这主要是因为我无法理解python如何循环遍历数组,或者我必须循环遍历数组的选项 我想构建一个数组:4列,18行 我需要每行的第一列是person_列表中的人名。然后,我将每隔3行增加到下一个人 看起来我的循环并没有像我预期的那样在数组中循环。似乎它将第一列中的所有值设置为等于person_列表值循环遍历python数组,将特定值设置为指定列,python,python-3.x,Python,Python 3.x,我尝试了很多东西,但仍然坚持。这主要是因为我无法理解python如何循环遍历数组,或者我必须循环遍历数组的选项 我想构建一个数组:4列,18行 我需要每行的第一列是person_列表中的人名。然后,我将每隔3行增加到下一个人 看起来我的循环并没有像我预期的那样在数组中循环。似乎它将第一列中的所有值设置为等于person_列表值 person_list = ["person1", "person2","person3","person4","person5","person6"] my_array
person_list = ["person1", "person2","person3","person4","person5","person6"]
my_array = [[0]*4]*len(person_list)*3
i=0
j=1
for row in my_array:
while j <= 3:
row[0] = person_list[i]
j+=1
j=1
i+=1
您可以使用模
%
以一定的间隔递增。例如,行%3==0
将以3的倍数返回True
。仅供参考,在上述代码中,您没有每隔3次重置行变量
person_list = ["person1", "person2","person3","person4","person5","person6"]
my_array = [[0]*4]*len(person_list)*3
j=0
i=0
for row in my_array:
if j%3==0:
row[0] = person_list[i]
i+=1
j+=1 # increment the row here
我认为你的代码一切都很好,你只是把它乘以3:
person_list = ["person1", "person2","person3","person4","person5","person6"]
my_array = [[0]*4]*len(person_list)
i=0
j=1
for row in my_array:
while j <= 3:
row[0] = person_list[i]
j+=1
j=1
i+=1
person\u list=[“person1”、“person2”、“person3”、“person4”、“person5”、“person6”]
我的数组=[[0]*4]*len(个人列表)
i=0
j=1
对于my_数组中的行:
而j问题似乎源于myu数组
的初始化方式。每一行都与其他行“嵌套”,我的意思是,如果您试图修改我的_数组[0],您将最终修改所有剩余的行。下面是一个例子来说明:
my_array[0].insert(0, 'hello_world')
# this prints:
# [['hello_world', 0, 0, 0],
['hello_world', 0, 0, 0],
....
['hello_world', 0, 0, 0]]
为了解决这个问题,您可以使用numpy来初始化零数组,或者执行如下操作:
my_array = [[0, 0, 0, 0] for i in range(18)]
要使代码更加简洁并打印预期输出,您可以执行以下操作:
for i in range(len(person_list)):
# person1 : idx 0, 1, 2
# person2 : idx 3, 4, 5
# ...
end_idx = (i + 1) * 3
start_idx = end_idx - 3
for sub_arr in arr[start_idx:end_idx]:
sub_arr.insert(0, person_list[i])
希望这有帮助 因此,我认为NeuralX有助于指出我创建阵列的方式不适用于我打算对其执行的操作。他是绝对正确的,当我运行更改时,它将更新最终数组中的每个条目
在使用嵌套列表的更多搜索中,我找到了如何创建数组,以便通过循环逐个更新嵌套列表。最终结果如下
person_list = ["person1", "person2","person3","person4","person5","person6"]
# The way I create the array appears the be the main root cause here. I need to create it like this
my_array = [[0 for x in range(4)] for y in range(sum(person_assessments))]
i=0
j=0
for person in person_list:
for assessment in range(1, 4):
my_array[i][0] = person
# print(person, ", ", assessment)
# print(i,", ", j,", ", person)
i+=1
j += 1
print(my_array)
抱歉,我编辑了我的答案以演示我预期的结果数组。我需要18行,然后乘以3,就得到了结果数组中的正确维数。所以x3是必需的。
person_list = ["person1", "person2","person3","person4","person5","person6"]
# The way I create the array appears the be the main root cause here. I need to create it like this
my_array = [[0 for x in range(4)] for y in range(sum(person_assessments))]
i=0
j=0
for person in person_list:
for assessment in range(1, 4):
my_array[i][0] = person
# print(person, ", ", assessment)
# print(i,", ", j,", ", person)
i+=1
j += 1
print(my_array)