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]
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)]
# 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]
a = [10, 20, 30 , 40, 50 , 60]
b = [30, 70, 110]
# take each value in a (multiply by 1.0 to get a double), and divide by the value in b in the corresponding index (i.e. indices 0,1 in a correspond with index 0 in b, and so on...)
c = [val*1.0/b[idx//2] for idx,val in enumerate(a)]
# here is the calculation using strings, to get the desired output by OP
d = ['{}/{}'.format(val, b[idx//2]) for idx,val in enumerate(a)]
print '{}\n{}'.format(c, d)
# Sum with a given window
def sumWithWindow(aList, window = 2):
res = []
mySum = 0
for i,elem in enumerate(aList):
mySum += elem
if (i+1) % window == 0:
res.append(mySum)
mySum = 0
return (res)
# Fraction with a given window
def fractionWithWindow(aList, window = 2):
res = []
b = sumWithWindow(aList, window)
for i,elem in enumerate(aList):
res.append(elem/b[int(i/window)])
return (res)
# Example
a = [10, 20, 30 , 40, 50 , 60]
print(sumWithWindow(a, 2))
print(fractionWithWindow(a,2))
这也是一行文风格的版本,有列表理解,可读性稍差,但非常简短:
# Sum with a given window
def sumWithWindow(aList, window = 2):
return [sum(aList[n:n+window]) for n in range(0,len(aList),window)]
# Fraction with a given window
def fractionWithWindow(aList, window = 2):
return [elem/sumWithWindow(aList,window)[i//window] for i,elem in enumerate(aList)]
# Example
a = [10, 20, 30 , 40, 50 , 60]
print(sumWithWindow(a, 2))
print(fractionWithWindow(a,2))
两个任务都可以使用列表理解(创建
b
和c
列表)如果确实需要分数,可以使用^{} 模块及其
Fraction
数据类型:注意
作为@劳伦斯。注意,在注释中,以上仅适用于大小为2的块(您称之为windows)。对于更一般的方法,您可以定义一个生成器,它将
yield
为您定义它们:例如
n = 3
:输出=
[0.3333333333333333, 0.6666666666666666, 0.42857142857142855, 0.5714285714285714, 0.45454545454545453, 0.5454545454545454]
下面是我的建议,其中一个函数用于求和,一个函数用于分数,列表和窗口宽度作为参数。它不使用外部包装,而且非常简短、易读和易懂:
这也是一行文风格的版本,有列表理解,可读性稍差,但非常简短:
相关问题 更多 >
编程相关推荐