将一个列表的元素除以另一列表的元素 [英] Dividing elements of one list by elements of another
问题描述
我有两个列表
a = [10, 20, 30 , 40, 50 , 60]
b = [30, 70, 110]
如您所见,列表b由列表的元素之和组成,窗口= 2:
As you can see, list b consists of a list's a sum of elements with window = 2:
b[0] = a[0] + a[1] = 10 + 20 = 30 etc.
我如何获得另一个列表,该列表由给定窗口的列表a元素和b元素的分数组成?在我的示例中,我想获取列表:
How can I get another list which will consist of fractions of list's a elements and b elemnts with a given window? In my example I want to get list:
c = [10/30, 20/30, 30/70, 40/70, 50/110, 60/110]
推荐答案
您可以对两个任务都使用列表理解(创建 b
和 c
列表)
You can use list-comprehensions for both tasks (creating b
and c
lists)
a = [10, 20, 30, 40, 50, 60]
b = [i+j for i, j in zip(a[::2], a[1::2])]
print(b) # [30, 70, 110]
c = [x / b[i//2] for i, x in enumerate(a)]
print(c) # [0.3333333333333333, 0.6666666666666666, 0.42857142857142855, 0.5714285714285714, 0.45454545454545453, 0.5454545454545454]
如果您确实想要分数,则可以使用 fractions
模块及其 Fraction
数据类型:
If you really want fractions, you can use the fractions
module and its Fraction
data type:
from fractions import Fraction
# same code as before
c = [Fraction(x, b[i//2]) for i, x in enumerate(a)]
print(c) # [Fraction(1, 3), Fraction(2, 3), Fraction(3, 7), Fraction(4, 7), Fraction(5, 11), Fraction(6, 11)]
注意
就像@LaurentH.注意在注释中,以上内容仅适用于大小为2的块(您称它们为 windows ).对于更通用的方法,您可以定义一个生成器,将生成 yield
为您:
Note
As @LaurentH. notices in the comments, the above works only for chunks (you call them windows) of size 2. For a more general approach, you can define a generator that would yield
them for you:
# taken from https://stackoverflow.com/a/312464/6162307
def yield_chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
b = [sum(chunk) for chunk in yield_chunks(a, 2)]
# same code
n = 3
的示例:
n = 3
b = [sum(chunk) for chunk in yield_chunks(a, n)]
print(b) # [60, 150]
c = [x / b[i//n] for i, x in enumerate(a)]
print(c) # [0.16666666666666666, 0.3333333333333333, 0.5, 0.26666666666666666, 0.3333333333333333, 0.4]
这篇关于将一个列表的元素除以另一列表的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!