gpt4 book ai didi

python - 如果已经看到某些东西,那么 Perl 模式的 python 等价物是什么?

转载 作者:太空狗 更新时间:2023-10-30 00:30:44 26 4
gpt4 key购买 nike

在 Perl 中,可以执行以下操作

for (@foo) {
# do something
next if $seen{$_}++;
}

我希望能够在 Python 中做同样的事情,即跳过已经执行过一次的 block 。

最佳答案

seen = set()
for x in foo:
if x in seen:
continue
seen.add(x)
# do something

参见 set文档以获取更多信息。

此外,itertools 底部的示例模块文档包含一个 unique_everseen 生成器,您可以像这样使用它:

for x in unique_everseen(foo):
# do something

关于python - 如果已经看到某些东西,那么 Perl 模式的 python 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2188863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com