Python - 每第 N 个索引追加列表
给定 2 个列表,每第 n 个索引将列表附加到原始列表。
Input : test_list = [3, 7, 8, 2, 1, 5, 8], app_list = [‘G’, ‘F’, ‘G’], N = 3
Output : [‘G’, ‘F’, ‘G’, 3, 7, 8, ‘G’, ‘F’, ‘G’, 2, 1, 5, ‘G’, ‘F’, ‘G’, 8]
Explanation : List is added after every 3rd element.
Input : test_list = [3, 7, 8, 2, 1, 5, 8, 9], app_list = [‘G’, ‘F’, ‘G’], N = 4
Output : [‘G’, ‘F’, ‘G’, 3, 7, 8, 2, ‘G’, ‘F’, ‘G’, 1, 5, 8, 9 ‘G’, ‘F’, ‘G’]
Explanation : List is added after every 4th element.
方法#1:使用循环
这是解决这个问题的蛮力方法,在这种情况下,每个第 n 个索引,内循环用于附加所有其他列表元素。
Python3
# Python3 code to demonstrate working of
# Append List every Nth index
# Using loop
# initializing list
test_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing Append list
app_list = ['G', 'F', 'G']
# initializing N
N = 3
res = []
for idx, ele in enumerate(test_list):
# if index multiple of N
if idx % N == 0:
for ele_in in app_list:
res.append(ele_in)
res.append(ele)
# printing result
print("The appended list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Append List every Nth index
# Using extend()
# initializing list
test_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing Append list
app_list = ['G', 'F', 'G']
# initializing N
N = 3
res = []
for idx, ele in enumerate(test_list):
# if index multiple of N
if idx % N == 0:
# extend to append all elements
res.extend(app_list)
res.append(ele)
# printing result
print("The appended list : " + str(res))
输出:
The original list is : [3, 7, 8, 2, 1, 5, 8, 9, 3]
The appended list : [‘G’, ‘F’, ‘G’, 3, 7, 8, ‘G’, ‘F’, ‘G’, 2, 1, 5, ‘G’, ‘F’, ‘G’, 8, 9, 3]
方法#2:使用extend()
解决这个问题的另一种方法。在这里,我们使用 extend 来获取每个第 N 个索引中的所有元素,而不是内部列表。
蟒蛇3
# Python3 code to demonstrate working of
# Append List every Nth index
# Using extend()
# initializing list
test_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing Append list
app_list = ['G', 'F', 'G']
# initializing N
N = 3
res = []
for idx, ele in enumerate(test_list):
# if index multiple of N
if idx % N == 0:
# extend to append all elements
res.extend(app_list)
res.append(ele)
# printing result
print("The appended list : " + str(res))
输出:
The original list is : [3, 7, 8, 2, 1, 5, 8, 9, 3]
The appended list : [‘G’, ‘F’, ‘G’, 3, 7, 8, ‘G’, ‘F’, ‘G’, 2, 1, 5, ‘G’, ‘F’, ‘G’, 8, 9, 3]