简体   繁体   English

在 Python 中将一个数组拆分为另一个数组

[英]Split an array inside another in Python

I am trying to write a code that compares two arrays ('a' and 'b)' and do something like that, getting the 'c' array:我正在尝试编写一个代码来比较两个数组('a' 和 'b)' 并执行类似的操作,获取 'c' 数组:

a = [1, 2, 2, 3, 3, 5] a = [1, 2, 2, 3, 3, 5]

b = [1, 2, 3] (It is taken from 'a' randomly) b = [1, 2, 3] (随机取自 'a')

c = [2, 3, 5] c = [2, 3, 5]

The problem I have is very simple since the algorithm is ok.我的问题很简单,因为算法没问题。 The code I am using is:我正在使用的代码是:

vetor1 = [1, 2, 2, 3, 3, 5]
vetor2 = sorted(random.sample(vetor1, 3))
inter = np.intersect1d(vetor1, vetor2)

cont_array2 = []
for i in range(len(inter)):
    cont2 = 0
    for j in range(len(vetor2)):
        if inter[i]==vetor2[j]:
            cont2 = cont2 + 1   
    cont_array2.append(cont2)

cont_array1 = []
for i in range(0,len(inter),1):
    cont1 = 0
    for j in range(0, len(vetor1), 1):
        if inter[i]==vetor1[j]:
            cont1 = cont1 + 1   
    cont_array1.append(cont1)

n_elements = np.subtract(cont_array1, cont_array2)

vetor2_1 = []
for i in range(len(n_elements)):
    if n_elements[i]!=0:
        vetor2_1.append(inter[i]*np.ones(n_elements[i]))

vetor2_2 = []
for data1 in vetor1:
    if data1 not in inter:
        vetor2_2.append(data1)

vetor3 = sorted(vetor2_1 + vetor2_2)
print(vetor3) 

The result I am getting is:我得到的结果是:

[array([2.]), array([3.]), 5]

I imagine the problem is in:我想问题在于:

vetor2_1.append(inter[i]*np.ones(n_elements[i]))

Because:因为:

print(vetor2_1)

Gives me:给我:

[array([2.]), array([3.])]

What should I do since I am not receving as answer [2, 3, 5]?既然我没有收到答案 [2, 3, 5],我该怎么办?

IIUC, you can turn all your algorithm into one line: IIUC,你可以把你所有的算法变成一行:

a = [1, 2, 2, 3, 3, 5]

b = [1, 2, 3]

c = [a.pop(a.index(i)) for i in b] #Works even with strings.

Output:输出:

[2, 3, 5]

If you need to parametrize something, you can turn it into a function.如果你需要参数化某些东西,你可以把它变成一个函数。 This will work with sorted(random.sample(vetor1, 3)) , but I didn't use it for replicability.这将适用于sorted(random.sample(vetor1, 3)) ,但我没有将它用于可复制性。

//generating a random index for array a, to take 3 elements out of it
my_random_int = random.randint(0,len(a)-2)

//popping the element out of the array to put them in b

for x in range(0,2):
    b[x]=a.pop(my_random_int+x)

sources:来源:

https://www.programiz.com/python-programming/methods/list/pop https://www.programiz.com/python-programming/methods/list/pop

https://www.edureka.co/blog/generate-random-number-in-python/ https://www.edureka.co/blog/generate-random-number-in-python/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM