Python跳过负值

时间:2015-09-12 16:03:08

标签: python skip

所以我有以下代码来查找最少3个给定值,其中abc,xyz,mnl是包含要比较的值的列表:

for q , (a,b,c) in enumerate(zip(abc,xyz,mnl)):
    print (a,b,c)
    if int(a) < int(b) & int(a) < int(c):
        print "a","\t",a
    elif int(b) < int(a) & int(b) < int(c):
        print "b","\t",b
    elif int(c) < int(a) & int(c) < int(b):
        print "c","\t",c

我得到了这个输出

('3137775', '-7589493', '-1419231')
('6199235', '-3810275', '-8726482')
('2649229', '-4119818', '3726604')
b    -4119818
('-1960710', '2758796', '9426184')
a   -1960710

问题是它在2次迭代时打印最小值'b',并在打印之前跳过3次迭代。并且它在每次迭代时继续这样做,其中包含多个负值(-ve)的值,我们可以在第一次迭代中看到'-7589493', '-1419231'

为什么它不能打印每次迭代的最小值

4 个答案:

答案 0 :(得分:2)

略有不同的方法:

abc = ('1', '2', '3')
xyz = ('3', '1', '2')
mnl = ('2', '3', '1')

for q , (a,b,c) in enumerate(zip(abc,xyz,mnl)):
    (aa, bb, cc) = (int(a), int(b), int(c))
    print(aa, bb, cc)
    m = min(aa, bb, cc)
    index = (aa, bb, cc).index(m)
    print 'abc'[index], m

# output:
(1, 3, 2)
a 1
(2, 1, 3)
b 1
(3, 2, 1)
c 1

我离开了您的示例中的qenumerate,即使它未被使用。

答案 1 :(得分:2)

As hiro says,您可以使用min功能。但是,如果您愿意,这应该有效:

abc = (1,2,3)
xyz = (2,3,1)
mnl = (3,1,2)

for q , (a,b,c) in enumerate(zip(abc,xyz,mnl)):
    print (a,b,c)
    a,b,c=int(a),int(b),int(c)
    if b > a < c:
        print ("a",a)
    elif a > b < c:
        print ("b",b)
    elif b > c < a:
        print ("c",c)

输出:

(1, 2, 3)
a 1
(2, 3, 1)
c 1
(3, 1, 2)
b 1

答案 2 :(得分:0)

这是我的方法:

for q, tup in enumerate(zip(abc, xyz, mnl)):
    combo = ((int(x), y) for x, y in zip(tup, 'abc'))
    # example of combo: ((5, 'a'), (2, 'b'), (8, 'c'))
    print '{1}\t{0}'.format(*min(combo))

这里的关键是计算组合。在这种方法中,tup是3个字符串的元组,例如('5', '2', '8')combo是转换为int后使用标签['a', 'b', 'c']压缩的元组的组合

答案 3 :(得分:-1)

&它的二进制AND,不是逻辑AND

试试这个:

for q, (a, b, c) in enumerate(zip(abc, xyz, mnl)):
    print(a, b, c)
    if int(c) > int(a) < int(b):
        print("a", "\t", a)
    elif int(c) > int(b) < int(a):
        print("b", "\t", b)
    elif int(b) > int(c) < int(a):
        print("c", "\t", c)

或使用AND逻辑运算符:

for q, (a, b, c) in enumerate(zip(abc, xyz, mnl)):
    print(a, b, c)
    if int(a) < int(b) and int(a) < int(c):
        print("a", "\t", a)
    elif int(b) < int(a) and int(b) < int(c):
        print("b", "\t", b)
    elif int(c) < int(a) and int(c) < int(b):
        print("c", "\t", c)