16

I have two lists like this:

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

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

What I want to do with these two list is make a third list, let's call it bananasplit.

I have to strip away ' \n', leaving only values and then make a formula which divides into:

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

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

I experimented with while-loop but can't get it right. Here is what I did:

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

How would you demolish this minor problem?

4

4 回答 4

27

The following will do it:

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

As far as your original code goes, the main issue is that the following are effectively no-ops:

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

To turn them into something useful, you would need to assign the results somewhere, e.g.:

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

Finally, it is worth noting that, depending on Python version, dividing one integer by another using / either truncates the result or returns a floating-point result. See In Python 2, what is the difference between '/' and '//' when used for division?

于 2013-01-21T08:11:45.890 回答
2

Try something like this.

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

If you want the float result (in python 2.x), you can change the ints to be float, or from __future__ import division

于 2013-01-21T08:11:52.943 回答
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]

>>> 
于 2013-01-21T08:17:18.730 回答
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函数。

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

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

于 2013-01-21T08:26:06.760 回答