我有一个名为“organizer”的函数,它需要两个值,一个列表和一个索引(数字),来重新组织这个列表,然后返回一个新列表。
我想执行此函数 10 次以创建 10 个列表并将此列表添加到单个列表列表中以供以后使用,程序完成了此操作,但是它重复最后一个列表 10 次,它不添加其他列表.
我把“组织者”功能放在这里,因为我无法找到问题所在,所以可能需要更多信息。 我一直在函数中使用 print 函数来查看它在哪里失败,并且它根据我的需要创建了列表,问题是在创建它们之后,它只是在循环进行时多次复制最后创建的列表。它需要生成最终列表并复制多次
这是代码:
number_list = ["12","11","10","9","8","7","6","5","4","3","2","1"]
indexes = [0,5,6,8,10,4,5,2,1,9]
def organizer(list,index): # Takes a list and reorganize it by a number which is an index.
number1 = index - 1
count_to_add = -1
list_to_add = []
for item in range(number1):
count_to_add += 1
a = list[count_to_add]
list_to_add.append(a)
number2 = index - 1
for item1 in range(number2):
del list[0]
list.extend(list_to_add)
return list
def lists_creator(list_indexes): # Create a list of 10 lists ,with 12 elements each.
final_list = []
count = -1
for item in list_indexes:
count += 1
result = organizer(number_list, list_indexes[count])
final_list.append(result)
return final_list
final_output = lists_creator(indexes)
print(final_output)
这是结果:(相同的列表 10 次)
[['7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8'], ['7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8'], ['7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8'], ['7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8'], ['7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8'], ['7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8'], ['7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8'], ['7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8'], ['7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8'], ['7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8']]
注意:如果我更改 list_creator 函数中的第 28 行
final_list.append(result)
对于
final_list.extend(result)
结果是:
['12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '8', '7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '3', '2', '1', '12', '11', '10', '9', '8', '7', '6', '5', '4', '8', '7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '12', '8', '7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '4', '3', '2', '1', '12', '11', '10', '9', '8', '7', '6', '5', '3', '2', '1', '12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8', '7', '6', '5', '4', '7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8']
这是我想要的结果,但不是一组列表。
最佳答案
您每次都使用相同的列表,因此结果实际上由一个列表组成,
在您的 list_creator
方法中,您必须向 organizer
方法提供原始列表 number_list
的副本,否则您只需进行变异即可再次列出相同的列表:
def lists_creator(list_indexes): # Create a list of 10 lists ,with 12 elements each.
final_list = []
count = -1
for item in list_indexes:
count += 1
result = organizer(list(number_list), list_indexes[count])
final_list.append(result)
return final_list
关于python - 如何将一个列表添加到另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58057459/