0

我是python新手,我很困惑。谁能向我解释从列表中制作集合的两种变体的区别?哪一个更正确?

a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]
c = set([])
d = set([])
for i in range (len(a)):
    c.add(a[i])

for y in range (len(b)):
    d.add(b[y])
print c.difference(d)    
import sets
e= sets.Set(a)
print e
f = sets.Set(b)
print f
print e.difference(f)

Outcome
set(['Jake', 'Eric'])
Set(['Jake', 'Eric'])

谢谢!

4

1 回答 1

1

将列表转换为集合不需要 for 循环:

a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]
print set(a) - set(b)

使用setobject 而不是sets.Set(),sets.Set()已被弃用。

于 2013-03-01T11:24:10.330 回答