简体   繁体   English

Python - 在不使用插入函数的情况下在特定索引处插入元素

[英]Python - insert element at specific index without using insert function

just a heads up.只是抬头。 My code probably is way off.我的代码可能已经过时了。 I'm new and i'm trying my best to figure it out but i'm struggling我是新手,我正在尽最大努力弄清楚,但我正在挣扎

So far i have this:到目前为止,我有这个:

def insert_value(my_list, value, insert_position):

    new_list = []
    for i in range(len(my_list)):
        if i == insert_position:
            new_list.append(value)
            i += 1

            return new_list

this is the code calling my function:这是调用我的函数的代码:

str_list3 = ['one','three','four', 'five', 'six']
new_list = list_function.insert_value(str_list3, 'two', 1)
print(new_list)
str_list4 = ['i', 't']
str_list4 = list_function.insert_value(str_list4, 'p', 0)
print(str_list4)
str_list4 = list_function.insert_value(str_list4, 's', -1)
print(str_list4)
str_list4 = list_function.insert_value(str_list4, 's', 7)
print(str_list4)

and:和:

num_list2 = [1, 3, 4, 5, 6]
num_list2 = list_function.insert_value(num_list2, 2, 1)
print(num_list2)

Am i far off in my solution?我的解决方案离我很远吗? I really want to understand where i'm going wrong我真的很想了解我哪里出错了

Output is meant to be:输出应为:

['one', 'two', 'three', 'four', 'five', 'six']
['p', 'i', 't']
['s', 'p', 'i', 't']
['s', 'p', 'i', 't', 's']

and:和:

[1, 2, 3, 4, 5, 6]]

my output is:我的输出是:

['two']
['p']
None

this is all i get这就是我得到的全部

You are actually extremely close, you just need to add some boundary checks:你实际上非常接近,你只需要添加一些边界检查:

def insert_value(my_list, value, insert_position):
    if insert_position < 0:
        insert_position = 0
    elif insert_position >= len(my_list):
        insert_position = len(my_list)
    
    new_list = []
    for i in range(len(my_list)):
        if i == insert_position:
            new_list.append(value)
        new_list.append(my_list[i])
    
    if len(my_list) == insert_position:
        new_list.append(value)
    
    return new_list
    
str_list3 = ['one', 'three', 'four', 'five', 'six']
new_list = insert_value(str_list3, 'two', 1)
print(new_list)
str_list4 = ['i', 't']
str_list4 = insert_value(str_list4, 'p', 0)
print(str_list4)
str_list4 = insert_value(str_list4, 's', -1)
print(str_list4)
str_list4 = insert_value(str_list4, 's', 7)
print(str_list4)

num_list2 = [1, 3, 4, 5, 6]
num_list2 = insert_value(num_list2, 2, 1)
print(num_list2)

Output:输出:

['one', 'two', 'three', 'four', 'five', 'six']
['p', 'i', 't']
['s', 'p', 'i', 't']
['s', 'p', 'i', 't', 's']
[1, 2, 3, 4, 5, 6]

You're pretty close except that you've neglected to insert the lines from the original list and you return inside the loop instead of after its done.您非常接近,只是您忽略了从原始列表中插入行并且您在循环内返回而不是在完成后返回。 Also, there is no need to increment i .此外,无需增加i Its reassigned on the next loop with the next value from range .它在下一个循环中使用range的下一个值重新分配。 Basically, range takes the place of the increment.基本上, range取代了增量。

def insert_value(my_list, value, insert_position):
    new_list = []
    for i in range(len(my_list)):
        if i == insert_position:
            new_list.append(value)
        new_list.append(my_list[i])
    return new_list

str_list3 = ['one','three','four', 'five', 'six']
new_list = insert_value(str_list3, 'two', 1)
print(new_list)

Instead of range you could use enumerate which counts but also gives you the lines iterated, so you don't have to index the array again.您可以使用enumerate代替range计数,但也可以为您提供迭代的行,因此您不必再次索引数组。

def insert_value(my_list, value, insert_position):
    new_list = []
    for i,v in enumerate(my_list):
        if i == insert_position:
            new_list.append(value)
        new_list.append(v)
    return new_list
    
str_list3 = ['one','three','four', 'five', 'six']
new_list = insert_value(str_list3, 'two', 1)
print(new_list)

You already have a few response on this question.你已经对这个问题有了一些回应。 Here is another option to consider:这是要考虑的另一种选择:

def insert_value(my_list, value, insert_position):
    if insert_position < 0:
        insert_position = (-insert_position) - 1

    #if you want any negative value to result in position 0
    #then your insert_position assignment will be
    #if insert_position < 0: insert_position = 0
    #the rest of the code will remain the same

    my_list.insert(insert_position,value)

    return my_list

str_list3 = ['one','three','four', 'five', 'six']
new_list = insert_value(str_list3, 'two', 1)
print(new_list)
str_list4 = ['i', 't']
str_list4 = insert_value(str_list4, 'p', 0)
print(str_list4)
str_list4 = insert_value(str_list4, 's', -1)
print(str_list4)
str_list4 = insert_value(str_list4, 's', 7)
print(str_list4)

num_list2 = [1, 3, 4, 5, 6]
num_list2 = insert_value(num_list2, 2, 1)
print(num_list2)

The output for these will be:这些输出将是:

['one', 'two', 'three', 'four', 'five', 'six']
['p', 'i', 't']
['s', 'p', 'i', 't']
['s', 'p', 'i', 't', 's']
[1, 2, 3, 4, 5, 6]

#custom function for insert #自定义插入函数

insert_value =lambda a,value,idx: a[:idx] + [value] + a[idx:]

example例子

str_list3 = ['one','three','four', 'five', 'six']
new_list = insert_value(str_list3, 'two', 1)
print(new_list)
str_list4 = ['i', 't']
str_list4 = insert_value(str_list4, 'p', 0)
print(str_list4)
str_list4 = insert_value(str_list4, 's', -1)
print(str_list4)
str_list4 = insert_value(str_list4, 's', 7)
print(str_list4)

num_list2 = [1, 3, 4, 5, 6]
num_list2 = insert_value(num_list2, 2, 1)
print(num_list2)

The output for these will be:这些输出将是:

['one', 'two', 'three', 'four', 'five', 'six']
['p', 'i', 't']
['s', 'p', 'i', 't']
['s', 'p', 'i', 't', 's']
[1, 2, 3, 4, 5, 6]

Another example but source list will change if need you can copy it另一个示例,但源列表会根据需要更改,您可以复制它

Syntax: lst[index:index] = [obj]语法:lst[index:index] = [obj]

Here is without custom function这里没有自定义功能

str_list = ['one','three','four', 'five', 'six']
str_list[1:1]=['two']
print(str_list)

str_list1=['i', 't']
str_list1[0:0]='p'
print(str_list1)
str_list1[-1:-1]=['s']
print(str_list1)
str_list1[7:7]=['s']
print(str_list1)

num_list2 = [1, 3, 4, 5, 6]
num_list2[1:1]=[2]
print(num_list2)

The output for these will be:这些输出将是:

['one', 'two', 'three', 'four', 'five', 'six']
['p', 'i', 't']
['s', 'p', 'i', 't']
['s', 'p', 'i', 't', 's']
[1, 2, 3, 4, 5, 6]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果没有插入函数,我们可以使用 python 编程在数组索引中插入新元素吗? - without insert function can we do insert new element in array index using python programming? 如何在不使用 python 循环的情况下将元素插入 3d numpy 数组中的特定索引? - How to insert element to a specific index in 3d numpy array without using python loops? 如何在python列表中的特定索引处插入元素 - how to insert a element at specific index in python list 将元素插入列表(不使用 Python 的 list.insert(index, item) 函数) - Inserting elements into list (without using Python's list.insert(index, item) function) 在不使用 insert() 的情况下将项目插入 Python 列表 - Insert an item to a Python list without using insert() 在 python 列表中的任意索引处插入一个元素 - Insert an element at an arbitrary index in python list 使用ElementTree将XML元素插入到特定位置 - Insert XML element to a specific location using ElementTree Python 中是否有 function 用于在具有约束的数据结构中插入元素 - Is there a function in Python to insert an element in a data structure with constraints 我想向空列表的特定索引插入一些元素 - I want to insert some element to specific index of empty list 如何使用 python 在 XML 文件的特定位置插入特定元素/文本? - How do I insert a specific element/text at a specific location in an XML file using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM