Python - 在列表中的每个第 N 个元素之后插入
有时我们需要在Python中执行一次插入,这可以在 insert函数的帮助下轻松完成。但有时,我们需要在每 n 个数字之后以重复的方式插入,因为可以有许多简写,非常方便。让我们讨论一些可以做到这一点的方法。
方法 #1:使用join() + enumerate()
我们可以使用 join函数将第 n 个子字符串中的每一个与数字 K 连接起来,并且 enumerate 可以完成执行列表选择性迭代的任务。
# Python3 code to demonstrate
# inserting K after every Nth number
# using join() + enumerate()
# initializing list
test_list = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r',
'g', 'e', 'e', 'k', 's']
# printing original list
print ("The original list is : " + str(test_list))
# initializing k
k = 'x'
# initializing N
N = 3
# using join() + enumerate()
# inserting K after every Nth number
res = list(''.join(i + k * (N % 3 == 2)
for N, i in enumerate(test_list)))
# printing result
print ("The lists after insertion : " + str(res))
The original list is : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]
The lists after insertion : [‘g’, ‘e’, ‘e’, ‘x’, ‘k’, ‘s’, ‘f’, ‘x’, ‘o’, ‘r’, ‘g’, ‘x’, ‘e’, ‘e’, ‘k’, ‘x’, ‘s’]
方法 #2:使用itertools.chain()
此方法还具有使用迭代器执行类似任务的能力,因此提高了性能。此函数执行类似的任务,但使用链方法连接n个子字符串。
# Python3 code to demonstrate
# inserting K after every Nth number
# using itertool.chain()
from itertools import chain
# initializing list
test_list = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r',
'g', 'e', 'e', 'k', 's']
# printing original list
print ("The original list is : " + str(test_list))
# initializing k
k = 'x'
# initializing N
N = 3
# using itertool.chain()
# inserting K after every Nth number
res = list(chain(*[test_list[i : i+N] + [k]
if len(test_list[i : i+N]) == N
else test_list[i : i+N]
for i in range(0, len(test_list), N)]))
# printing result
print ("The lists after insertion : " + str(res))
The original list is : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]
The lists after insertion : [‘g’, ‘e’, ‘e’, ‘x’, ‘k’, ‘s’, ‘f’, ‘x’, ‘o’, ‘r’, ‘g’, ‘x’, ‘e’, ‘e’, ‘k’, ‘x’, ‘s’]