在可能更小的列表中插入无序元素的标准方法是什么?

问题描述 投票:0回答:1

我有:

msg: list = []

预期行为:

msg.insert(2,"two")   # msg = [None, None, "two"]
msg.insert(10,"ten")  # msg = [None, None, "two", None, None, None, None, None, None, None, "ten"]

当前代码:

def insert_into_list(orig_list: list, index: int, element: str)->None: # does not need to return the list
    if index >= len(orig_list): # sanity checks removed for MRE
        for _ in range(index - len(orig_list) + 1):
            orig_list.append(None)
    orig_list.insert(index, element)

是否有更好的(或者比编写另一种方法更标准且可能更短)的方法来做到这一点?

python list insert
1个回答
0
投票

这里有一些可能值得尝试的事情。

code00.py

#!/usr/bin/env python

import sys
from typing import Any


def insert_fill(lst: list, index: int, element: Any, fill: Any = None):
    l = len(lst)
    if index < l:
        lst.insert(index, element)
        return
    lst += [fill] * (index - len(lst))
    lst.append(element)


def main(*argv):
    l = []
    insert_fill(l, 2, "two")
    insert_fill(l, 10, "ten")
    print(l)
    insert_fill(l, 1, "one")
    print(l)


if __name__ == "__main__":
    print(
        "Python {:s} {:03d}bit on {:s}\n".format(
            " ".join(elem.strip() for elem in sys.version.split("\n")),
            64 if sys.maxsize > 0x100000000 else 32,
            sys.platform,
        )
    )
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

输出

(py_pc064_03.10_test0) [cfati@cfati-5510-0:/mnt/e/Work/Dev/StackExchange/StackOverflow/q078325531]> python ./code00.py 
Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] 064bit on linux

[None, None, 'two', None, None, None, None, None, None, None, 'ten']
[None, 'one', None, 'two', None, None, None, None, None, None, None, 'ten']

Done.
© www.soinside.com 2019 - 2024. All rights reserved.