首页 > 解决方案 > 如何将列表中的每 10 个数字除以 10?

问题描述

我有一个包含 100 万个数字的列表,例如:

[1,2,3,4,5,6,7,8,9,100,11,12,13,14,15,16,17,18,19,200,.......]

其中每 10 个数字是应有的 10 倍。我想更正列表,以便每 10 个数字除以 10。

我已经尝试过for i%10==0 then i=i/10,但它似乎不适用于列表。

标签: pythonpython-2.7

解决方案


You can achieve this with a conditional inside a list comprehension, conditioning on the position of the element (via enumerate):

X = [1,2,3,4,5,6,7,8,9,100,11,12,13,14,15,16,17,18,19,200]

# Quotient on 9 because lists are 0-indexed
y = [x/10. if i%10==9 else x for i, x in enumerate(X)]

print(y)
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10.0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20.0]

推荐阅读