简体   繁体   English

Python:在其他内部循环

[英]Python: while loop inside else

def is_prime(x):     
    count = 1
    my_list = []
    while count > 0 and count < x:
        if x % count == 0:
            my_list.append(x/count)
        count += 1
    return my_list
my_list = is_prime(18)

def prime(x):

    my_list2 = []
    for number in my_list:
        if number <= 2: 
            my_list2.append(number)
        else:
            count = 2
            while count < number:
                if number % count == 0:
                    break
                else: 
                    my_list2.append(number)
                count += 1
    return my_list2
print prime(18)

Just started out with Python. 刚开始使用Python。 I have a very simple question. 我有一个非常简单的问题。

This prints: [9, 3, 2] . 打印: [9, 3, 2]

Can someone please tell me why the loop inside my else stops at count = 2? 有人可以告诉我为什么我的else循环在count = 2处停止吗? In other words, the loop inside my loop doesn't seem to loop. 换句话说,我的循环内部的循环似乎没有循环。 If I can get my loop to work, hopefully this should print [2, 3] . 如果我可以使循环正常工作,则希望可以打印[2, 3] Any insight is appreciated! 任何见解表示赞赏!

Assuming that my_list2 (not a very nice name for a list) is supposed to contain only the primes from my_list , you need to change your logic a little bit. 假设my_list2 (不是一个很好的列表名称)应该只包含my_list的素数,则需要稍微更改一下逻辑。 At the moment, 9 is being added to the list because 9 % 2 != 0 . 目前, 9被添加到列表中,因为9 % 2 != 0 Then 9 % 3 is tested and the loop break s but 9 has already been added to the list. 然后测试了9 % 3并给出了循环break s,但9已添加到列表中。

You need to ensure that each number has no factors before adding it to the list. 在将每个数字添加到列表之前,需要确保每个数字没有任何影响。

There are much neater ways to do this but they involve things that you may potentially find confusing if you're new to python. 有很多更巧妙的方法可以做到这一点,但是如果您是python的新手,它们可能会使您感到困惑。 This way is pretty close to your original attempt. 这种方式非常接近您的原始尝试。 Note that I've changed your variable names! 请注意,我已经更改了您的变量名! I have also made use of the x that you are passing to get_prime_factors (in your question you were passing it to the function but not using it). 我还利用了您传递给get_prime_factorsx (在您的问题中,您将其传递给函数但未使用)。 Instead of using the global my_list I have called the function get_factors from within get_prime_factors . 我没有使用全局my_listget_factorsget_prime_factors调用了函数get_prime_factors Alternatively you could pass in a list - I have shown the changes this would require in comments. 或者,您可以传递一个列表-我已经在注释中显示了需要进行的更改。

def get_factors(x):
    count = 1
    my_list = []
    while count > 0 and count < x:
        if x % count == 0:
            my_list.append(x/count)
        count += 1
    return my_list

# Passing in the number                   # Passing in a list instead
def get_prime_factors(x):                 # get_prime_factors(factors):
    prime_factors = []
    for number in get_factors(x):         #     for number in factors:
        if number <= 2:
            prime_factors.append(number)
        else:
            count = 2
            prime = True
            while count < number:
                if number % count == 0:
                    prime = False
                count += 1
            if prime:
                prime_factors.append(number)

    return prime_factors

print get_prime_factors(18)

output: 输出:

[3, 2]

Just to give you a taste of some of the more advanced ways you could go about doing this, get_prime_factors could be reduced to something like this: 只是为了让您了解一些可以执行此操作的更高级的方法,可以将get_prime_factors简化为以下形式:

def get_prime_factors(x):
    prime_factors = []
    for n in get_factors(x):
        if n <= 2 or all(n % count != 0 for count in xrange(2, n)):
            prime_factors.append(n)
    return prime_factors

all is a built-in function which would be very useful here. all都是内置函数,在这里将非常有用。 It returns true if everything it iterates through is true . 它返回true ,如果它通过迭代,一切都是true xrange ( range on python 3) allows you to iterate through a list of values without manually specifying a counter. xrange (python 3上的range )允许您遍历值列表,而无需手动指定计数器。 You could go further than this too: 您也可以走得更远:

def get_prime_factors(x):
    return [n for n in get_factors(x) if n <= 2 or all(n % c != 0 for c in xrange(2, n))]

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

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