简体   繁体   English

检查数组中的每个元素是否满足特定要求

[英]Checking every element in an array for a specific requirement

I need to check every element in an array to see if it can be divided by 5 or more different numbers, if not - drop it into a different array.我需要检查数组中的每个元素,看看它是否可以除以 5 个或更多不同的数字,如果不能 - 将其放入不同的数组中。

For example, I have an array [3,32,6,8,0,16,3,45] and I have to get a result of [3,5,8,0,3]例如,我有一个数组 [3,32,6,8,0,16,3,45] 我必须得到 [3,5,8,0,3] 的结果

I tried going for a simple while loop inside a for loop:我尝试在 for 循环中进行一个简单的 while 循环:

for i in array:
    n = 0
    div = 1
    while n <= 4 and div <= i:
        if i % div == 0:
            n += 1
        div += 1

    if n <= 4:
        sub_array.append(i)

return sub_array

It works just fine, but I need to make it so it will check the division with elements and not indexes.它工作得很好,但我需要让它检查元素而不是索引的划分。 The moment I change all 'i' to 'array[i]': "list index out of range".当我将所有 'i' 更改为 'array[i]' 时:“列表索引超出范围”。 Is there any way to solve this issue?有没有办法解决这个问题?
The reason why I'm trying to improve this code is because the tester I am using to check it returns errors from time to time.我试图改进此代码的原因是因为我用来检查它的测试器不时返回错误。

When you do for i in array it means the 'i' is the element in the array.当您for i in array这意味着“i”是数组中的元素。 If you want to iterate with using array[i] you should use for i in range(len(array))如果你想使用array[i]进行迭代,你应该使用for i in range(len(array))

The modified code is as follows:修改后的代码如下:

for i in range(len(array)):
    n = 0
    div = 1
    while n <= 4 and div <= array[i]:
        if array[i] % div == 0:
            n += 1
        div += 1

    if n <= 4:
        sub_array.append(array[i])

return sub_array

what I've understood from your question is that if any of the numbers from an array is not divisible by 5, you want them to be put into a different array.我从您的问题中了解到,如果数组中的任何数字不能被 5 整除,您希望将它们放入不同的数组中。 So, I've written this code for you.所以,我已经为你编写了这段代码。 I hope it will solve your problem.我希望它能解决你的问题。

array = [3,32,6,8,0,16,3,45]
subarray = []
for i in array:
    if i%5==0:
        continue
    else:
        subarray.append(i)

print(subarray)

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

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