看着一个元组中的数字

时间:2012-12-18 19:40:19

标签: python

现在我的功能不是将列表中的数字识别为数字。我试图配对两个列表中的项目,然后根据mul的值将它们排序到不同的列表中。但一切都进入了负面清单。如何确保它将mul视为每个if语句中的数字。

def balance_equation(species,coeff):
  data=zip(coeff,species)
  positive=[]
  negative=[]
  for (mul,el) in data:
    if mul<0:
        negative.append((el,mul))
    if mul>0:
        positive.append((el,mul))

编辑; 我最初包括这个 balance_equation([ 'H2O', 'A2'],[ '6', ' - 4'])

3 个答案:

答案 0 :(得分:1)

嗯,第一个问题是你的函数只返回None,只是扔掉了两个列表,所以甚至无法看到它是否做得对。

如果你解决了这个问题,你会发现 正在做正确的事情。

def balance_equation(species,coeff):
  data=zip(coeff,species)
  positive=[]
  negative=[]
  for (mul,el) in data:
    if mul<0:
        negative.append((el,mul))
    if mul>0:
        positive.append((el,mul))
  return negative, positive

>>> n, p = balance_equation(balance_equation('abcdef', range(-3,3))
>>> n
[('a', -3), ('b', -2), ('c', -1)]
>>> p
[('e', 1), ('f', 2)]

所以,有两种可能性:

  1. 由于您粘贴的代码显然不是您正在运行的实际代码,因此您可能会修改错误,同时将其重写为此处发布。
  2. 你没有用明智的投入来称呼它。例如,如果向后传递参数,因为species可能是字符串的集合,所以它们最终都是正面的。或者,同样地,如果您将coeffs作为整数的字符串表示传递。
  3. 如果这是最后一个问题 - 你正在传递,比如'abcdef', ['-3', '-2', '-1', '0', '1', '2', '3'],你想在balance_equation而不是在调用代码中处理它,这很容易。只需在zip

    之前添加此行
    coeff = [int(x) for x in coeff]
    

    或者将您的zip更改为:

    data = zip((int(x) for x in coeff), species)
    

    顺便说一句,我假设您使用的是CPython 2.在Python 3中,尝试将字符串比较为0将会引发TypeError而不是始终返回True,而在其他情况下Python 2实现它可能总是返回False而不是True ...

答案 1 :(得分:1)

您的问题在于,在您调用它的方式(balance_equation(['H2O','A2'],['6','-4']))中,mul是字符串而不是int('6''-4'而不是{{1} }或6)。将您的if语句更改为:

-4

这会将if int(mul)<0: negative.append((el,mul)) if int(mul)>0: positive.append((el,mul)) 转换为整数,然后再将其与0进行比较。

答案 2 :(得分:0)

我认为你有答案,但在Python中也有一种更简单的方法:

for (mul, el) in data:
    append_to = negative.append if mul < 0 else positive.append
    append_to(el)

不确定0“应该发生什么”,但