def _get_apps(path):
    """gets only all the apps"""

    return {app for app in os.listdir(path) if ".py" not in app}

apps = _get_apps(r"C:\Users\Hello\Desktop\Test")
css_apps = _get_apps(r"C:\Users\Hello\Desktop\Test2")

print(apps.difference(css_apps))


我正在尝试弄清桌面中两个文件夹之间的区别。使用上面的代码

单独的输出是正确的,它按预期返回一个集合

个别印刷:

print(apps)

print(css_apps)


输出:

{Music}

{Music,Css}


但是做:

print(apps.difference(css_apps))


输出:

set()


这是怎么回事?

它按预期返回了一个集合,但是以某种方式我无法对返回的集合执行集合操作。

最佳答案

这是因为difference操作会计算apps集中的元素,而不是css_apps集中的元素。现在没有满足此条件的元素,因此您会得到一个空集合。

s.difference(t)创建一个:


  在s中但在t中没有元素的新集合


也许,您需要的是.symmetric_difference()。这将创建一个新集合,其中两个集合中都包含元素。

In [1]: s1 = set([1]) # First set

In [2]: s2 = set([1,2]) # Second set

In [3]: s1.difference(s2) # Creates a new set with elements in s1 but not in s2
Out[3]: set() # empty because no elements satisfy this criteria

In [4]: s2.difference(s1)  # Creates a new set with elements in s2 but not in s1
Out[4]: {2} # element '2' exists in s2 but not in s1

In [5]: s1.symmetric_difference(s2) # Returns new set with elements in either s1 or s2 but not both
Out[5]: {2}

In [6]: s2.symmetric_difference(s1)
Out[6]: {2}

关于python - 设置怪异行为(Python),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32809508/

10-15 11:48