python - 如何在不使用插入的情况下将某些内容添加到特定位置的列表中
问题描述
请给一些建议。我对编程相当陌生,并且正在从事一项任务,我需要在指定位置的列表中添加一些值。赋值的参数是必须使用循环,并且不能使用除 range() 或 append() 之外的任何内置函数。
我得到的错误是底部的第 4 行显示“TypeError:只能将列表(而不是“int”)连接到列表”,我不知道如何解决这个问题。任何建议将不胜感激!请注意 - 因为这是一个任务,所以我不是在寻找代码,而是关于我哪里出错以及如何解决它,因为我想学习和理解的建议!
my_list = [1, 2, 3, 4, 5, 4, 1, 4, 6]
#function 1 - takes list as parameter and returns length
def length(my_list):
count = 0
for x in my_list:
count = count + 1
return count
#function 5 - returns a copy of the list with the value inserted at the specified pos
def insert_value(my_list, value, insert_position):
count = 0
new_list = []
if insert_position > length(my_list):
new_list = my_list.append(value)
elif insert_position < 0:
new_list = value + my_list
while count < insert_position:
new_list = my_list[:insert_position]
count= count + 1
new_list = new_list + value
new_list = new_list[insert_position+1:]
return new_list
print(insert_value(my_list, 11, 6))
解决方案
您的问题是您不能将整数添加到列表中。您只能将两个类似列表的对象添加在一起。
所以,new_list = [value] + my_list
对于那个特殊情况。
一般来说,我会使用列表切片。例如:
original_list = [0,1,2,3,5,6,7]
value_to_insert = 4
position_to_insert = 4
new_list = original_list[:position_to_insert] + [value_to_insert] + original_list[position_to_insert:]
如果必须使用循环:
new_list = []
for i in range(length(my_list)):
new_list.append(my_list[i])
if i == insert_position:
new_list.append(my_list(value_to_insert))
return new_list
最后:
my_list = [1, 2, 3, 4, 5, 4, 1, 4, 6]
#function 1 - takes list as parameter and returns length
def length(my_list):
count = 0
for x in my_list:
count = count + 1
return count
#function 5 - returns a copy of the list with the value inserted at the specified pos
def insert_value(my_list, value, insert_position):
new_list = []
for i in range(length(my_list)):
new_list.append(my_list[i])
if i == insert_position:
new_list.append(value)
return new_list
print(insert_value(my_list, 11, 6))
推荐阅读
- javascript - Trouble connecting to blue-tooth devices using node noble on Windows
- centos7 - repmgr - Automate process of making primary to standby after failover
- android - how to use DPAD controls of remote in recycler view?
- xml - 在 xsl 中根据 xml 深度插入空格
- django - How to add a time stamp for all the fields in a model django
- java - 创建 FlatFileItemWriter bean 时出错
- c# - A* Neo4j 返回边缘上的所有路径和条件
- google-apps-script - 如果另一个单元格不为空,则更新单元格 - Google 脚本
- android - 适配器引用生成的类 (android-sunflower)
- powershell - 将广告用户标题设置为组名