【问题标题】:Getting values from all the indices of a list (Determining Prime Numbers)从列表的所有索引中获取值(确定素数)
【发布时间】:2016-01-16 06:11:57
【问题描述】:

首先,我是 Python 新手。我正在尝试使用模运算% 来确定一个数字,比如 167 是否是质数。

例如, 让167 % n = some value i

167 % 1167 % 167 时,它应该返回0,对于range(2,166) 中的n,它应该给出167 % n 的余数。我遇到的问题是我试图在167 % nn = 1 ~ 167 打印余数,但不知道如何获取列表索引的值(应该是余数)。

所以,这就是我所拥有的:

L  = [] #creates empty list
i=0     #initialize i? 
for i in range(1, 168) :
if 167 % i == 0  :
    print ("There is no remainder")
else :
    167 % i == x   # x should be the value of the remainder 
    L[i].append(x) #attempting to add x ... to the indices of a list. 
    print(L[x])    #print values of x.

如果我可以使用while循环就更好了,那应该会更清楚。因此,虽然 i 从 1 到 167 迭代,但它应该将结果 x 添加到列表的索引中,我想打印这些结果。

有什么推荐的吗?任何帮助表示赞赏!非常感谢。

【问题讨论】:

    标签: python python-3.x while-loop


    【解决方案1】:

    这会创建一个包含所有不等于零的余数的列表:

    L  = []
    for i in range(1, 168) :
        remainder = 167 % i
        if remainder == 0  :
            print("There is no remainder")
        else:
            L.append(remainder)
            print(remainder)
    
    >>> len(L)
    165
    

    你的代码有很多问题:

    • 您的缩进错误。
    • 在循环之前设置i = 0 没有意义,因为它没有在循环之前使用并且在循环中被覆盖。
    • 这:167 % i == x 将余数与不存在的x 进行比较。您想用x = 167 % i 将结果分配给x
    • 您尝试使用L[i].append(x) 在索引i 处附加L 的元素,但您想使用L.append(x)x 附加到L
    • 最后,您尝试使用print(L[x]) 获取刚刚添加的值,但您需要使用print(L[i]),更简单,只需打印remainderprint(remainder)

    【讨论】:

    • 谢谢!我才意识到这个列表是多余的!
    猜你喜欢
    • 2017-03-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 2012-10-14
    • 2016-10-11
    • 2014-08-16
    • 2021-10-06
    • 1970-01-01
    相关资源
    最近更新 更多