我有一张黑名单
input_list = [0,1,2,3,4,5,6,...]我正在寻找一种以这种方式按百分比值进行除法的方法:因此,对于50%的拆分,它将在两个列表之间均分数组。
out1,out2 = splitArrayby(input_list,0.5)
>> [0,2,4,6,...] , [1,3,5,7,...]对于66%,它将把第一个项目到第一个列表,然后两个项目到第二个列表。
out1,out2 = splitArrayby(input_list,0.66)
>> [0,3,6,...] , [1,2,4,5,7,8,..]跳跃比保持精确的比率更重要。因此,如果输入数组中的最后项未被平均分配,则可以。
可能可以用for循环来完成。有没有更多的“毕多尼”的方式来做这件事?
发布于 2020-08-10 10:37:02
在纯python中,没有numpy,您可以在下面的匿名函数上使用过滤器操作符。
l = list(filter(lambda x : input_list.index(x)%2==0, input_list))
# includes [0, 2, 4, 6]
l = list(filter(lambda x : input_list.index(x)%2==1, input_list))
# includes [1, 3, 5]这里,您将测试元素的索引是奇数还是事件。
对于0.66,您只需使用%2==0与%2==1或%2==2
l = list(filter(lambda x : input_list.index(x)%3==1 or input_list.index(x)%3==2, input_list))发布于 2020-08-10 10:40:05
在zar3bski解决方案之前,我使用numpy创建了解决方案:
import math
def splitArrayBy(idx,pattern):
fullmask = ([0]*pattern[0]+[1]*pattern[1])*math.ceil(len(idx)/sum(pattern))
fullmask = np.array(fullmask[:len(idx)])
if isinstance(idx,(np.ndarray))==False:
idx = np.array(idx)
out0 = idx[np.where(fullmask==0)]
out1 = idx[np.where(fullmask==1)]
return out0,out1例如,它的工作方式:
idx=[0,1,2,3,4,5,6,7,8,9,10,11]
out0,out1 = splitArrayBy(idx,[1,1])
>> (array([ 0, 2, 4, 6, 8, 10]), array([ 1, 3, 5, 7, 9, 11]))
out0,out1 = splitArrayBy(idx,[2,1])
>>(array([ 0, 1, 3, 4, 6, 7, 9, 10]), array([ 2, 5, 8, 11]))发布于 2020-08-10 10:57:35
其中一种方法是首先确定所需拆分的比例。然后,我们可以使用分子循环列表和分母作为步骤大小。这就产生了第一部分,第二部分就是这个结果的对应部分。
import numpy as np
from decimal import Decimal
a_list = list(range(42))
split = .7
split_ratio = Decimal(str(split)).as_integer_ratio()
part_a = []
counter = 0
for i in range(0, split_ratio[0]):
part_a.extend(a_list[i::split_ratio[1]])
part_a.sort()
part_b = np.setdiff1d(a_list, part_a).tolist()示例输出:
>>> part_a
[0, 1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 15, 16, 20, 21, 22, 23, 24, 25, 26, 30, 31, 32, 33, 34, 35, 36, 40, 41]
>>> part_b
[7, 8, 9, 17, 18, 19, 27, 28, 29, 37, 38, 39]https://stackoverflow.com/questions/63338198
复制相似问题