为什么列表理解跳过列表的元素?
今天,通过列表理解为任务创建新的解决方案时,获得了有趣的结果。
def checkio(array: list) -> int:
if array:
return sum([x for x in array if array.index(x) % 2 == 0]) * array[-1]
else:
return 0
assert checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30"
assert checkio([1, 3, 5]) == 30, "(1+5)*5=30"
assert checkio([6]) == 36, "(6)*6=36"
assert checkio([]) == 0, "An empty array = 0"
assert checkio([-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]) == 1968
当我决定进行调试时,我已经看到第十六个元素被跳过了。为什么?在互联网上,我没有找到描述这个原因。
Today get the interesting result when creating a new solution for the task by list comprehension.
def checkio(array: list) -> int:
if array:
return sum([x for x in array if array.index(x) % 2 == 0]) * array[-1]
else:
return 0
assert checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30"
assert checkio([1, 3, 5]) == 30, "(1+5)*5=30"
assert checkio([6]) == 36, "(6)*6=36"
assert checkio([]) == 0, "An empty array = 0"
assert checkio([-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]) == 1968
When I decided to do debugging I have seen that the sixteenth element was skipped. Why? On the Internet, I didn't find describe this cause.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
array.index(x)将返回该值的第一次出现的索引,因此,如果您在数组中具有重复项而无法使用。您可以查看此答案,您可以实现自己想要的东西列表切片:
array.index(x) will return the index of the first occurrence of that value, thus if you have duplicates in the array that would not work. You can look at this answer, you could achieve what you want with a list slicing: