为了账号安全,请及时绑定邮箱和手机立即绑定

Python 函数行为

Python 函数行为

开心每一天1111 2024-01-24 15:22:52
如果我有一个使用以下形式的元组列表 构建最小堆结构的函数: [(vertex),length,(another_vertex),...........],我将该函数写入采用两个输入:堆结构和先前形式的称为三元组的新元素。它应该根据“(顶点)”从添加的三元组中构建没有重复项的堆,并根据“长度”以升序方式构建堆,我将其编写如下:def heap_add_or_replace(heap, triplet):   heap.append(triplet)   # Sorting according to the first element of every triplet to have duplicates get next to each other   vertexSort = sorted(heap, key = lambda x: x[0])   # Sorting according to the distance in ascending manner   lenSort = sorted(vertexSort, key = lambda x: x[1])   # Function to remove duplicates   def remvDuplicate(struct):     check = set()     result = []     for i in struct:        if i[0] not in check:            result.append(i)            check.add(i[0])     return result  # Setting the final return value  heap = remvDuplicate(lenSort)return heap我的问题是使用以下两种方法调用函数有什么区别:triplet_heap = list()a = heap_add_or_replace(triplet_heap,((2,3),0.9,(1,0)))print("the new heap is: " + str(a))b = heap_add_or_replace(triplet_heap,((7,2),0.3,(2,2)))print("the new heap is: " + str(b))和,new_heap = list()heap_add_or_replace(new_heap,((2,3),0.9,(1,0)))print("the new heap is: " + str(new_heap))heap_add_or_replace(new_heap,((7,2),0.3,(2,2)))print("the new heap is: " + str(new_heap))因为在第二种方法中该函数的行为不正确:正确的输出 - 第一次调用:新堆是: [((2, 3), 0.9, (1, 0))]新堆是: [((7, 2), 0.3 , (2, 2)), ((2, 3), 0.9 , (1, 0))]错误的输出 - 第二次调用:新堆是: [((2, 3), 0.9, (1, 0))]新堆是: [((2, 3), 0.9 , (1, 0)), ((7, 2), 0.3 , (2, 2))]提前致谢。
查看完整描述

2 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

在第一种情况下,即“正确的情况”,您正在查看函数的返回值heap_add_or_replace

在第二种情况下,即“不正确的情况”,您将查看list每次将原始数据传递给heap_add_or_replace函数时会发生什么情况。

在该函数中,您在第一次进行排序时heap_add_or_replace复制输入。list排序的结果以及此后所做的所有操作都不会反映在原始列表中。因此,您传入的原始列表永远不会被排序或过滤重复项。这就是两个案例不同的原因。


查看完整回答
反对 回复 2024-01-24
?
哔哔one

TA贡献1854条经验 获得超8个赞

以下是与您的两种情况类似的情况:


a = []


def f(l):

    l.append(0) #affect global variable a

    l = 5       #new local variable created inside the function

    return l    #return l = 5!


#first case

b = f(a)        #b is assigned value from return l (5)


#second case

print(a)        #printing global variable not result from function ([0])


查看完整回答
反对 回复 2024-01-24
  • 2 回答
  • 0 关注
  • 40 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信