下面的函数将列表插入到指定位置的另一个列表中。
在保留外部支架的同时从输出中移除中间括号的最佳方法是什么?
def insert(list1, list2, index):
pos = 0
new_list = []
if index > len(list1):
index = len(list1)
elif index < 0:
index = 0
for pos in range(0, index):
new_list.append(list1[pos])
#for pos in range(1):
new_list.append(list2)
while index != len(list1):
new_list.append(list1[index])
index += 1
return new_list
list1 = ["b", "o", "o", "m"]
list2 = ["r", "e", "d"]
index = 2
new_list = insert(list1, list2, index)
print(new_list)
输出:
['b', 'o', ['r', 'e', 'd'], 'o', 'm']
答案 0 :(得分:1)
您只需使用list slicing即可获得所需的结果:
list1 = ["b", "o", "o", "m"]
list2 = ["r", "e", "d"]
index = 2
print list1[:index]+list2+list1[index:]
>>> ['b', 'o', 'r', 'e', 'd', 'o', 'm']
要将其细分,列表切片的工作方式为lst[start:end]
所以,
list1 = ["b", "o", "o", "m"]
index = 2
print list1[:index]
>>> ['b', 'o']
print list1[index:]
>>> ['o', 'm']
所以现在我们将列表分成两部分,然后我们使用+
运算符连接列表以连接第一部分,list2和第二部分,并获得结果最终列表。
如果你想将事物封装在一个函数中,那么:
def insert(list1, list2, index):
return list1[:index]+list2+list1[index:]
答案 1 :(得分:0)
只需用list.extend()替换list.append()。
def insert(list1, list2, index):
pos = 0
new_list = []
if index > len(list1):
index = len(list1)
elif index < 0:
index = 0
for pos in range(0, index):
new_list.extend(list1[pos])
#for pos in range(1):
new_list.extend(list2)
while index != len(list1):
new_list.extend(list1[index])
index += 1
return new_list
list1 = ["b", "o", "o", "m"]
list2 = ["r", "e", "d"]
index = 2
new_list = insert(list1, list2, index)
print(new_list)
输出:
['b', 'o', 'r', 'e', 'd', 'o', 'm']
答案 2 :(得分:0)
在您对第一篇文章的评论中,您说您无法使用extend()。这是一种不需要的方式:
lists = ['b', 'o', ['r', 'e', 'd'], 'o', 'm']
new_list = []
for i in lists:
if isinstance(i, list):
for i2 in i:
new_list.append(i2)
continue
new_list.append(i)
print(new_list)
输出:
$ python is.py
['b', 'o', 'r', 'e', 'd', 'o', 'm']