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)
可能有更短版本的代碼可以執行此操作,但這也可以工作。
添加回答
舉報