我是python的新手,我需要一些帮助。我有使用C / C ++但不是python的经验。我只是需要一些帮助。
我不明白这条线在做什么。
S = {-4 , 4 ,-3 , 3, -2 , 2, -1, 1, 0};
{x for x in S if x >= 0}
我知道S是一套。我知道我们正在通过集合S进行循环,但我不知道的是" x"之前做的循环?当我使用print函数时,我得到错误说:
NameError: name 'x' is not defined
谢谢!
答案 0 :(得分:0)
由于您熟悉其他编程语言,因此以下是处理算法的三种方法。
result
通过set comprehension,其中x
的范围仅限于理解。被认为是最pythonic,通常最有效。
result_functional
,功能等同于result
,但在使用lambda
时比设置理解实现更不优化。此处x
的范围限定为匿名lambda
函数。
result_build
,完整的循环,通常效率最低。
S = {-4 , 4 ,-3 , 3, -2 , 2, -1, 1, 0}
result = {x for x in S if x >= 0}
# {0, 1, 2, 3, 4}
result_functional = set(filter(lambda x: x >= 0, S))
# {0, 1, 2, 3, 4}
result_build = set()
for x in S:
if x>= 0:
result_build.add(x)
print(x)
# 0
# 1
# 2
# 3
# 4
assert result == result_build
assert result == result_functional