[英]Python inserting to a list when index > len(list)
我想我有一個很簡單的問題,但是,我很困惑。
我需要做的就是在列表中插入一些內容,如下所示:
list = ["apples", "oranges", "more apples"]
list.insert(10, "pears")
不導致此:
["apples", "oranges", "more apples", "pears"]
索引4到9必須有多個空白空間,就像在Lua或Ruby中使用nil值一樣。 我可以使用for循環來填補空白,但是,我將無法對其進行迭代並將其插入列表的開頭(因為它將把其他所有內容推到一邊)。 任何想法表示贊賞!
您需要填寫清單。
def padded_insert(lst, at_idx, value):
if len(lst) <= at_idx:
npads = at_idx - len(lst) + 1
lst += [ None ] * npads # or '' or 0 or whatever...
lst[at_idx] = value
您是否考慮過切換到詞典並將索引用作其鍵?
dict = {1: 'apples',
2: 'oranges',
3: 'more apples'}
dict[10] = 'pears'
所以字典將是:
{1: 'apples', 2: 'oranges', 3: 'more apples', 10: 'pears'}
恕我直言,我認為您不需要列表即可實現自己的目的。
這里:
def insert_with_pad(arr, index, val):
if len(arr) <= index:
pad_length = index - len(arr)
arr = arr + ['' for i in range(pad_length)] + [val]
else:
# No need to pad
arr[index] = val
return arr
輸入:
insert_with_pad(['a', 'b'], 3, 'w')
輸出:
['a', 'b', '', 'w']
為此我做了一個小功能:
def insert(item, pos, lst):
if pos > len(lst):
return lst+[None]*(pos-len(lst))+[item]
else:
lst.insert(pos, item)
return lst
但是,只需一行即可使用:
pos = 10
item = pears
lst += [None]*(pos-len(lst))+[item]
僅當索引大於列表的長度時才有效。 或做一個混亂的方法是:
if pos>len(lst): lst+=[None]*(pos-len(lst))+[item]
else: lst.insert(pos, item)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.