5 回答
TA贡献1820条经验 获得超2个赞
numpy 能够将列表拆分为均匀分布的较小列表。您可以在np.array_split列表本身中指定拆分数量。n在这里,我使用 math.floor 来获取该值进入列表长度的偶数次。在本例中,n=3列表有 12 个元素,因此它将返回 4 作为结果子列表的数量。
该[np.append(x,l1) for x....部分表示将 l1 中的值附加到每个子列表的末尾。并将chain_from_iterable它们全部混合在一起,您可以将其呈现为列表list()。
l1它还有在最后添加值的副作用,如果您不想这样做,可以使用切片来删除最后一个n值,其中n是列表的长度l1。
import numpy as np
import itertools
import math
n = 3
l1 = ["a","b"]
l2 = ["j","k","l","m","n","o","p","q","r","s","t","u"]
list(itertools.chain.from_iterable([np.append(x, l1) for x in np.array_split(l2,math.floor(len(l2)) / n)]))
或者如果您不想尾随附加:
list(itertools.chain.from_iterable([np.append(x,
l1) for x in np.array_split(l2,
math.floor(len(l2)) / n)]))[:-len(l1)]
TA贡献1893条经验 获得超10个赞
list3 = []
n = 3
for x in range(1, len(list2)+1):
if x%n == 0 and x != len(list2):
list3.append(list2[x-1])
for y in list1:
list3.append(y)
else:
list3.append(list2[x-1])
print(list3)
TA贡献1818条经验 获得超3个赞
只需迭代列表 b 的每个第 n 个元素并插入列表 a 的每个迭代即可。
a = ["a", "b"]
b = ["j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u"]
n = 3 # where you want to insert
while n < len(b):
for i in range(len(a)):
b.insert(n, a[i])
n += 1 # increment n by 1 so 'b' insert after 'a'
n += 3 # increment n by 3 every iteration to insert list a
print(b)
结果:['j', 'k', 'l', 'a', 'b', 'm', 'n', 'o', 'a', 'b', 'p', 'q' , 'r', 'a', 'b', 's', 't', 'u']
TA贡献2051条经验 获得超10个赞
list1= ["a","b"]
list= ["j","k","l","m","n","o","p","q","r","s","t","u"]
d=[]
for i in list:
print(list.index(i))
if ((list.index(i)+1)%3==0 and list.index(i)!=0):
d.append(i)
d.extend(list1)
else:
d.append(i)
print(d)
TA贡献1942条经验 获得超3个赞
one = ["a","b"]
two = ["j","k","l","m","n","o","p","q","r","s","t","u"]
start =0
end = 3 #or whatever number you require
complete_list=[]
iterations = int(len(two)/3)
for x in range(iterations):
sub_list= two[start:end]
start = start+3
end= end+3
complete_list.append(sub_list)
if x < iterations-1:
complete_list.append(one)
complete_list = flatten(complete_list)
可能有更短版本的代码可以执行此操作,但这也可以工作。
添加回答
举报