为什么列表理解跳过列表的元素?

发布于 2025-01-24 05:33:51 字数 542 浏览 0 评论 0原文

今天,通过列表理解为任务创建新的解决方案时,获得了有趣的结果。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情场扛把子 2025-01-31 05:33:51

array.index(x)将返回该值的第一次出现的索引,因此,如果您在数组中具有重复项而无法使用。您可以查看此答案,您可以实现自己想要的东西列表切片:


arr = [-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]
print(arr[::2])

Out:
[-37, -19, 29, 3, -64, 36, 26, 55, 84, -65]

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:


arr = [-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]
print(arr[::2])

Out:
[-37, -19, 29, 3, -64, 36, 26, 55, 84, -65]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文