所以我有一个奇怪的问题......
我想处理一个数组并从中自然舍入索引。
例如,如果你有数组...
pies = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
我想把它的每一个1.1元素自然地舍入。所以在这种情况下:
pies[0::round(1.1x)]
输出:
[0, 1, 2, 3, 4, 6, 7, 8, 9]
因为它会取出以下四舍五入的位置:
pies[0]->pies[0]
pies[1.1]->pies[1]
pies[2.2]->pies[2]
pies[3.3]->pies[3]
pies[4.4]->pies[4]
pies[5.5]->pies[6]
pies[6.6]->pies[7]
pies[7.7]->pies[8]
pies[8.8]->pies[9]
请注意,我们并未对内容进行四舍五入 - 我们正在对索引进行四舍五入。
作为另一个例子,请考虑:
pies = [0, 2, 5, 1, 3, 9, 2, 12, 33, 45]
pies[0::round(1.1x)]
输出:
[0, 2, 5, 1, 3, 2, 12, 33, 45]
我想知道你怎么能以最'pythonic'的方式做到这一点。
谢谢!
答案 0 :(得分:2)
In [7]: pies = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [8]: stride=1.1
In [9]: [pies[x] for x in range(len(pies)) for x in [int(round(x*stride))] if x < len(pies)]
Out[9]: [0, 1, 2, 3, 4, 6, 7, 8, 9]
另一方面,对于生成器函数来说这似乎是一个很好的工作:
def rounding_iterator(seq, stride):
try:
i = 0
while True:
yield seq[int(round(i*stride))]
i += 1
except IndexError:
pass
pies = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print list(rounding_iterator(pies, 1))
print list(rounding_iterator(pies, 1.1))
print list(rounding_iterator(pies, .9))
结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9]
答案 1 :(得分:1)
我已对此进行了编辑,因此您需要使用1.1的增量索引并对其进行舍入。正确的吗?
如果是这样,它应该是这样的:
>>> pies = [0, 1, 2, 3, 3, 2, 1, 77, 88, 99]
>>> print [ pies[int(round(x*0.1+x))] for x in xrange(len(pies)-1) ]
[0, 1, 2, 3, 3, 1, 77, 88, 99]
>>> pies = [0, 2, 5, 1, 3, 9, 2, 12, 33, 45]
>>> print [ pies[int(round(x*0.1+x))] for x in xrange(len(pies)-1) ]
[0, 2, 5, 1, 3, 2, 12, 33, 45]
>>>
这是你想要的吗?
与numpy相同:
>>> import numpy as np
>>> pies = [0, 2, 5, 1, 3, 9, 2, 12, 33, 45]
>>> print [ pies[int(round(x))] for x in np.arange(0,len(pies)-1,1.1) ]
[0, 2, 5, 1, 3, 2, 12, 33, 45]
使用numpy,您可以更改乘数:
>>> print [ pies[int(round(x))] for x in np.arange(0,len(pies)/1.1,1.1) ]
[0, 2, 5, 1, 3, 2, 12, 33, 45]
>>> print [ pies[int(round(x))] for x in np.arange(0,len(pies)/3.3,3.3) ]
[0]
>>> print [ pies[int(round(x))] for x in np.arange(0,len(pies)/2.2,2.2) ]
[0, 5, 3]
>>>
答案 2 :(得分:0)
如何将列表中的值乘以1.1,将其四舍五入,并将其转换为int以删除小数:
pies = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for pie in pies:
print int(round(pie * 1.1))
答案 3 :(得分:0)
如果它不需要一行......
def rounded_indices(ls):
result = []
original_index = 0
new_index = 0
while new_index < len(ls):
result.append(ls[new_index])
original_index += 1
new_index = int(round(1.1 * original_index))
return result
>>> pies = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> rounded_indices(pies)
[0, 1, 2, 3, 4, 6, 7, 8, 9]