将一个列表除以另一个列表

时间:2013-01-21 08:09:30

标签: python list divide

我有两个这样的列表:

monkey = ['2\n', '4\n', '10\n']

banana = ['18\n', '16\n', '120\n']

我想用这两个列表做的是制作第三个列表,我们称之为bananasplit。

我必须剥离' \n',只保留值,然后制作一个分为以下公式:

bananasplit[0] = banana[0]/monkey[0]

bananasplit[1] = banana[1]/monkey[1]

我尝试使用while循环,但无法正确完成。这是我做的:

bananasplit = 3*[None]

i = 0

while i <= 2:

    [int(i) for i in monkey]

    [int(i) for i in banana]

    bananasplit[i] = banana[i]/monkey[i]

    i += 1

你会如何拆除这个小问题?

4 个答案:

答案 0 :(得分:20)

以下将会这样做:

>>> bananasplit = [int(b) / int(m) for b,m in zip(banana, monkey)]
>>> print(bananasplit)
[9, 4, 12]

就原始代码而言,主要问题是以下内容实际上是无操作:

[int(i) for i in monkey]
[int(i) for i in banana]

要将它们变成有用的东西,你需要在某处分配结果,例如:

monkey = [int(i) for i in monkey]
banana = [int(i) for i in banana]

最后,值得注意的是,根据Python版本,使用/将一个整数除以另一个整数会截断结果或返回浮点结果。见In Python 2, what is the difference between '/' and '//' when used for division?

答案 1 :(得分:2)

尝试这样的事情。

bananasplit = [x/y for x, y in zip(map(int, banana), map(int, monkey))]

如果您想要float结果(在python 2.x中),您可以将int更改为floatfrom __future__ import division

答案 2 :(得分:1)

列表迭代和地图功能可以让您快速到达目的地。

>>> monkey = ['2\n', '4\n', '10\n']

>>> banana = ['18\n', '16\n', '120\n']

>>> monkey = [ float(m.strip()) for m in monkey]

>>> banana = [ float(m.strip()) for m in banana]

>>> def div(a,b):

...     return a/b

... 

>>> map(div, banana, monkey)

[9.0, 4.0, 12.0]

>>> 

答案 3 :(得分:0)

列表理解,如[an_expression for some_variable in some_sequence],会返回列表。您的示例只是删除了这些结果。

# remove trailing whitespace and convert strings to numbers
monkey_numbers = [int(item.strip()) for item in monkey]
banana_numbers = [int(item.strip()) for item in banana]

# a traditional loop
bananasplit = [] # an empty list
for i in range(len(banana_numbers)):
  # make bananasplit longer on each iteration
  bananasplit.append(banana_numbers[i] / monkey_numbers[i])

然后,您可以使用列表推导而不是循环,因为您的表达式非常简单。您将需要zip function,其中包含两个列表并列出对。

# divide in one statement
bananasplit = [
  banana_portion / monkey_bunch 
  for (banana_portion, monkey_bunch) in 
  zip(banana_numbers, monkey_numbers)
]

当然,您可以自由使用较短的标识符;我使用长名称来使他们的角色更容易理解。