[英]Appending negative numbers (Python)
我正在创建一个程序,该程序将出于理性根定理的目的而得到一个数的所有因子(包括其负的对应数)。
我成功获得了肯定的根源,但似乎无法将否定的根源附加到列表中,而且它一直需要输入。 这是代码。
a = input("Number:")
c = []
for b in (1,a+1):
if a%b == 0:
c.append(b)
for d in c:
e = (-1)*d
c.append(d)
print c
因此,我尝试删除“ c.append(d)”部分,并将其替换为“ print e”。 并印出了负面因素。
1 日 , 随着你遍历它从来没有修改列表,总是有很高的几率要出事 。
第二 ,可以调用for b in (1,a+1)
,则需要一个range
的前(1, a+1)
作为,例如for b in range(1,a+1)
第三 ,如果print e
提供正确的信息,则e
必须包含要添加的内容。 因此,您只需在c.append(d)
下添加c.append(e)
c.append(d)
。
4 日 ,您所使用的input()
使我使用的是想python2.x 。 但是,如果是这种情况,请考虑使用int(raw_input())
而不是input()
。 如果您没有使用python2.x和python3.x,则将int()
强制转换为input()
以使int(input())
。
a = input("Number:")
c = []
for b in range(1,a+1):
if a%b == 0:
c.append(b)
temp = []
for d in c:
e = (-1)*d
temp.append(d)
temp.append(e)
for i in temp:
c.append(i)
print c
您要附加错误的变量。 尝试这个:
a = int(input("Number: "))
c = []
for b in range(1, a+1):
if a % b == 0:
c.append(b)
for d in c:
e = -1 * d
c.append(e) # append the negated number instead of the original...
是的,修改要迭代的列表是一个坏主意。 请尝试使用临时列表。
这可能更容易阅读
a = input("Number:")
positives = []
for i in range(1, a+1):
if a % i == 0:
positives.append(i)
negatives = [-x for x in positives]
print 'positives:', positives
print 'negatives:', negatives
在这里,您将永远追逐自己的尾巴。 由于您要为每个迭代附加一个新项目。 即。 您正在遍历“实时” c,而不是循环开始时的快照。
for d in c:
e = (-1)*d
c.append(d)
用列表理解替换它更简单
c += [-d for d in c]
这是一个片段,显示了动态扩展c
的问题
>>> for d in c:
... print -d
... c.append(-d)
...
-1
-2
-3
-4
-5
1
2
3
4
5
-1
-2
-3
-4
-5
1
2
3
4
5
-1
-2
-3
-4
-5
1
2
3
4
5
-1
-2
-3
-4
-5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.