2017-08-08 67 views
-3

我試圖在有序列表中添加一個值,但該列表將不會改變:爲什麼列表不變?

def insert(V, x): 

    if len(V)!=0: 

     for i in range(0 , len(V)-1): 
      if (V[i]<=x)and(V[i+1]>=x): 
       V=V[0:i+1]+[x]+V[i+1:len(V)] 
       print("\nExpected: \n"+ repr(V)) 
       return 

    V=V+[x] 
    return 

我有這樣的:

V=[1,2,3,4,5,6,7,8,9,10] 
insert(V, 6) 
print("\nResult: \n"+ repr(V))enter code here 

,這是結果:

Expected: 
[1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10] 

Result: 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

我可以解決問題設置V作爲返回,但我希望該功能在列表上工作。

+2

可能的重複[python;修改列表中的函數](https://stackoverflow.com/questions/22054698/python-modifying-list-inside-a-function) – AChampion

+0

是否有你不能使用'list.insert()'的原因? –

+0

'''v。插入(索引,值)''' –

回答

1

你在做什麼可以簡單地用list.insert完成。

至於爲什麼你的功能不工作,你需要更新使用全片分配原來的列表,以便傳遞給函數列表是通過電流參考V更新:

... 
V[:] = V[0:i+1] + [x] + V[i+1:len(V)] 
#^

請注意RHS(右手側)是一個新的列表對象。單獨指派給V將名稱/變量重新綁定到新的列表對象。但是,使用切片分配可確保使用新列表中的值更新原始列表。

+0

我知道我有更簡單的方法來做到這一點,但我正在學習另一個課程,我藉此機會修改python;) [我確信我已經做一些錯誤的句子] – Lorenzo

+0

mmm我不知道什麼rhs的意思是:P – Lorenzo

+0

@Lorenzo更新:) –

0

你可以你的價值只是追加到列表中,並隨後對其進行排序

l.append(值)

l.sort()

0

到位您的函數不改變V

V=V[0:i+1]+[x]+V[i+1:len(V)] 

這條線之後,V不再是傳遞給函數列表的引用,但另一個列表。此行不會更改第一個列表,但會創建一個新列表。

您必須return V然後得到結果或調用V的方法,例如list.insert()

-1

正如其他人指出的那樣,您並未修改原始列表。 (相反,你創建一個新的列表,然後也不回了。)

這裏有一個解決方案,它利用list.insert優勢,以修改現有的列表:

def insert(lst, value): 
    '''Insert a value into a sorted list in-place, while maintaining sort order''' 

    for i, x in enumerate(lst): 
     if x > value: 
      lst.insert(i, value) 
      return 

    # fallback, in case this is the new largest 
    lst.append(value) 

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
insert(a, 6) 
print(a) # [1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10] 

編輯

更多但可能難以閱讀:

def insert(lst, value): 
    lst.insert(next((i for i, x in enumerate(lst) if x > value), len(lst)), value)