函数在使用 insort(lst,ele) 时不返回值



我正在使用Bisect函数在python中编写一个简单的集合抽象。这里的问题是,当我使用 insort 函数在列表中添加数据时,该函数返回 None。但是当我使用BISECT时。BISECT(lst,ele),该函数返回的值将是列表的索引,如果需要,可以在列表中插入元素。

# Python program to implement collection abstraction
# using Bisect Algorithm
# The program would add an element into the SORTED LIST"
# which would be the input
# The program would test whether the element is in the collection
# And also, to return the element of the collection if it is there
from bisect import bisect
from bisect import insort_right
the_list = []
def add(lst,ele):
    return insort_right(lst,ele)
#def test(lst,ele)
#def remove(lst,ele):

print("Enter the size of the list:")
N = int(input())
for x in range(N):
    x = input("")    
    the_list.append(x)
    the_list.sort()
print(the_list)
print("Enter the element to be added in the list")
element = input("")
add_element = add(the_list,element)
print("The element is added in collection at location:", add_element)

insort 不返回值,因为它会更改列表本身。通常,以这种方式使用副作用的 Python 函数不会返回值。如果要从 add 返回修改后的列表,请执行以下操作:

def add(lst, ele):
    insort_right(lst, ele)
    return lst

但是这样做真的没有意义,因为返回的列表与传入的列表相同。调用上下文已经可以访问该列表,因此无需返回它,这样做有点不惯用。

最新更新