【问题标题】:Inserting the elements of a list to the middle of another list [duplicate]将列表的元素插入另一个列表的中间[重复]
【发布时间】:2020-12-06 05:50:16
【问题描述】:

我有一个这样的列表:

["*****", "*****"]

我想像这样将另一个列表的元素插入到这个列表的中间:

["*****", "abc", "ded", "*****"]

但是,我的尝试产生了一个嵌套在另一个列表中的列表:

["*****", ["abc", "ded"], "*****"]

这是我的代码:

def addBorder(picture):

    length_of_element = len(picture[0])
    number_of_asterisks = length_of_element + 2
    new_list = ['*' * number_of_asterisks for i in range(0, 2)]
    new_list.insert(len(new_list)//2, [value for value in picture])
    
    return new_list

我知道我的代码很好。我只是想知道我需要做哪些调整。

【问题讨论】:

  • 不,它不是重复的。我在理解切片符号时没有问题。我想将列表的元素而不是整个列表附加到另一个列表的中间。
  • Insert 在一个位置插入一个元素 - 而不是多个。切片列表:newlist = oldlist[:half] + data + newlist[half:]
  • 是的,但data 会做同样的事情。它只会将其添加为列表而不是单个元素。
  • list.insert() 不能以您想要的方式使用。您可以在循环中插入所有单个元素 - 或对列表进行切片。欺骗是这样做的。

标签: python list algorithm


【解决方案1】:
a = ['****', '****']
b = ['abc', 'efg']
mid_index = len(a)//2 # Integer result for a division

result = a[:mid_index] + b + a[mid_index:]

如果你想直接将结果赋值给a,你也可以简单:

a[mid_index:mid_index] = b

【讨论】:

  • mid_index = len(a) // 2 - 为什么要创建一个浮点数并投射它?
  • @PatrickArtner 你是对的,改了
猜你喜欢
  • 2013-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多