【问题标题】:Adding multiple times integer to the middle of the list [duplicate]将多次整数添加到列表的中间[重复]
【发布时间】:2021-11-07 06:42:13
【问题描述】:

我想在列表中间添加cb 整数。 这是我的代码:

listA.insert(int(len(listA)/2),b*c)
print("Your New List: ", listA)

当我将 (b*c) 更改为 ([b]*c) 时,它可以工作,但我稍后会将其转换为整数。因此,它必须是像[1,2,3,4,5] 而不是[1,2,[3],4,5] 这样的正式形式。如果我们说listA = [1,2,3,4,5],假设b = 2c = 3 我需要[1,2,2,2,2,3,4,5]。另外,我没有使用循环的权限。

【问题讨论】:

  • 如果你阅读Python documentation,你会看到insert函数“在给定位置插入一个项目”。所以它只能放一个元素。

标签: python python-3.x


【解决方案1】:

使用列表切片:

lst = [1,2,3]
middle = len(lst) // 2
lst[middle:middle] = [2] * 10

输出:

[1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3]

【讨论】:

    【解决方案2】:

    b * c 将返回一个整数值。所以这行不通。

    您可以使用数组切片和连接来执行此操作。

    listA = listA[0 : len(listA)//2] + [2] * 3 + listA[len(listA)//2 : len(listA)]
    

    编辑:

    根据 OPs 的评论,这个数组需要转换为一个整数。可以这样做:

    result = int("".join([str(number) for number in listA]))
    

    如果我把它们放在一起

    listA = [1, 2, 3, 4, 5]
    listA = listA[0 : len(listA)//2] + [2] * 3 + listA[len(listA)//2 : len(listA)]
    print(listA)
    result = int("".join([str(number) for number in listA]))
    print(result)
    

    以下是输出:

    [1, 2, 2, 2, 2, 3, 4, 5]
    12222345
    

    【讨论】:

    • 它可以工作,但在添加新元素后,正如我所说,我需要将列表转换为整数。我的意思是如果列表[1,2,3,4],我将其设为1234。因此,您的方法无法在我的代码中转换。
    • 确实如此。你只需要这样做:int("".join([str(number) for number in listA]))
    猜你喜欢
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 2022-08-02
    • 2013-12-23
    • 1970-01-01
    • 2015-12-04
    • 2020-05-23
    • 1970-01-01
    相关资源
    最近更新 更多