简体   繁体   English

从一行上的2个列表打印

[英]Printing from 2 lists on one line

What I have so far: 到目前为止我所拥有的:

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

I know this does not print anything. 我知道这不会打印任何东西。 What I have is a function that takes in two lists species=['H2O','O2','CO2'] and coeff=['1','3','-4'] . 我所拥有的是一个函数,它接受两个列表species=['H2O','O2','CO2']coeff=['1','3','-4'] I need it to print like so: 1H20+3O2=4CO2 我需要它像这样打印: 1H20+3O2=4CO2

I started by putting the negative coeff and species in one list and the positive in the other. 我首先将负系数和物种放在一个列表中,而将积极放在另一个列表中。 I just can seem to be able to get the two to print right. 我似乎能够让两个打印正确。

Try this: 尝试这个:

species = ["H2O", "CO2", "O2"]
coeff = ['1', '-4', '3']

pos = [c + s for c, s in zip(coeff, species) if int(c) > 0]
neg = [c[1:] + s for c, s in zip(coeff, species) if int(c) < 0]
print ("+".join(pos))+"="+("+".join(neg))

EDIT : I took out the spaces. 编辑 :我拿出空格。 2nd EDIT : coeff is a list of strings. 第二个编辑coeff是一个字符串列表。

You should also test if pos or neg are empty to replace them with 0 s when appropriate. 您还应测试posneg是否为空,以便在适当时用0秒替换它们。 It appears that the coefficients are integers. 似乎系数是整数。

Breaking things down into steps is a good way to solve things (you can always recombine the steps later), and you've got 80% of the way there. 将事情分解为步骤是解决问题的好方法(您可以随后重新组合这些步骤),并且您已经有80%的方法。

You already have positive and negative lists. 您已经有positivenegative列表。 So, you need to convert each one into a string, then just: 因此,您需要将每个转换为字符串,然后只需:

print poshalf, "=", neghalf

So, how do you convert positive into poshalf ? 那么,你如何将positive转换为poshalf Well, it's a representation of each member, separated by '+' , so if you had a function stringify that could turn each member into its representation, it's just: 好吧,它是每个成员的表示,用'+'分隔,所以如果你有一个函数stringify可以把每个成员变成它的表示,它只是:

poshalf = '+'.join(stringify(el, mul) for (el, mul) in pos)
neghalf = '+'.join(stringify(el, mul)[1:] for (el, mul) in neg)

The [1:] there is to take out the - sign. [1:]有取出-符号。 If mul is actually an integer rather than a string, it probably makes sense to just negate the value before passing it to stringify : 如果mul实际上是一个整数而不是一个字符串,那么在将值传递给stringify之前将其取消是有意义的:

neghalf = '+'.join(stringify(el, -mul) for (el, mul) in neg)

Now, what does that "stringify" function look like? 现在,那个“stringify”函数是什么样的? Well, each one member is an (el, mul) pair. 好吧,每个成员都是(el, mul)对。 If they were both strings, you could just add them. 如果它们都是字符串,您可以添加它们。 From your previous questions, mul may end up being some kind of number at this point, but that's almost as easy: 从你之前的问题来看, mul最终可能会成为某种数字,但这几乎一样容易:

def stringify(el, mul):
    return str(mul) + el

Put it all together, and you're done. 把它们放在一起,你就完成了。

One way to make this all simpler: If you never use the (el, mul) for any other purpose except to call stringify on it, just call stringify in the first place and store the result: 让这一切变得更简单的一种方法是:如果你从来没有将(el, mul)用于任何其他目的,除了调用stringify之外,只需首先调用stringify并存储结果:

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

Remember that last line, which you've left off both versions of your previous question and this question! 请记住最后一行,您已经从上一个问题和这个问题的两个版本中删除了! If you never return the values, all that effort figuring them out is wasted, and the caller just gets None as an answer. 如果你永远不会返回这些值,那么所有用来计算它们的努力都会被浪费掉,并且调用者只能得到None作为答案。

Obviously either the str or the int is unnecessary, but I've left them both in for safety; 显然,无论是str还是int都是不必要的,但为了安全起见,我们都将它们都留下了; you should look at your surrounding code and remove the unnecessary one. 您应该查看周围的代码并删除不必要的代码。 (If you're taking mul as an int, you probably want str(-mul) instead of str(mul)[1:] , as described earlier.) (如果你把mul作为int,你可能想要str(-mul)而不是str(mul)[1:] ,如前所述。)

Once you've got this, if you understand list comprehensions, you might realize that this is a familiar pattern: start with [] , loop over some other collection, and append each value that meets some test. 一旦你有了这个,如果你理解列表理解,你可能会意识到这是一个熟悉的模式:以[]开头,循环其他一些集合,并append满足某些测试的每个值。 In other words: 换一种说法:

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

You might notice that you can simplify this even further—the only thing you use the lists for is to build the strings, so maybe you just want a function that returns a string equation (in which case you can use a generator expression instead of a list comprehension—if you don't know about them yet, ignore that part). 您可能会注意到您可以进一步简化这一点 - 您使用列表的唯一方法是构建字符串,因此您可能只需要一个返回字符串方程的函数(在这种情况下,您可以使用生成器表达式而不是列表理解 - 如果您还不了解它们,请忽略该部分)。

def balance_equation(species,coeff):
  data=zip(coeff,species)
  positive = '+'.join(str(mul) + el for (mul, el) in data if int(mul) > 0)
  negative = '-'.join(str(mul) + el for (mul, el) in data if int(mul) < 0)
  return positive + '=' + negative

Of course now you're returning a string instead of a pair of lists, so you have to change your calling code to just print balance_equation(species, coeff) instead of combining the lists. 当然现在你要返回一个字符串而不是一对列表,所以你必须改变你的调用代码来print balance_equation(species, coeff)而不是组合列表。

One last thing: You seem to reverse the order of the coefficients/multipliers and species/elements at each call. 最后一件事:您似乎在每次调用时都会颠倒系数/乘数和种类/元素的顺序。 For example: 例如:

def balance_equation(species,coeff):
  data=zip(coeff,species)

Unless there's a good reason to do otherwise, it's better to pick one order and be consistent throughout, or you're invariably going to run into a bug where you get them backwards. 除非有充分的理由不这样做,否则最好选择一个订单并在整个过程中保持一致,否则你总会碰到一个让你倒退的错误。

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

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