python2:如何编辑set对象的每个部分?

2024-09-30 12:31:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我对集合有个小问题。所以我有一个叫做s的集合:

s = set(['Facebook', 'Yahoo', 'Gmail'])

我有一个叫做l的列表:

l = ['Yahoo', 'Google', 'MySpace', 'Apple', 'Gmail']

如何检查集合s中的哪些内容在我的列表l中?你知道吗

我也尝试过这样做,但是Python给了我一个错误:

TypeError: 'set' object does not support indexing 

因此,如果对象不支持索引,如何编辑对象的每个部分?你知道吗

谢谢。你知道吗


Tags: 对象内容apple列表facebookobject错误google
3条回答

为什么不试试这个作为你的第一个问题

[x for x in s if x in l]

对于第二个问题,我不明白您到底想做什么,但我认为只要一个带有项的简单for循环就可以做到,或者您可以使用iter(s)enumerate(s) 如果你一定需要索引(以为那些不是索引)

print s.intersection(l)

那是更有效的方法。就你而言:

s = set(['Facebook', 'Yahoo', 'Gmail'])
l = ['Yahoo', 'Google', 'MySpace', 'Apple', 'Gmail']
print s.intersect(l)

下面是效率较低的方法:

resset = []
for x in s:
    if x in l:
        resset.append(x)
print resset

另外,不要像这样声明一个集合:

s = set(['Facebook', 'Yahoo', 'Gmail'])

试试这个:

s = {'Facebook', 'Yahoo', 'Gmail'}

只是为了节省一些时间:)

测试交叉点:

s.intersection(l)

演示:

>>> s = set(['Facebook', 'Yahoo', 'Gmail'])
>>> l = ['Yahoo', 'Google', 'MySpace', 'Apple', 'Gmail']
>>> s.intersection(l)
set(['Yahoo', 'Gmail'])

你也可以用for循环来循环你的集合,但这并没有那么有效。你知道吗

相关问题 更多 >

    热门问题