Python 有人能给我解释一下从列表中生成集合的两种变体的区别吗?
我是python新手,我感到困惑。有人能给我解释一下从列表中生成集合的两种变体的区别吗?哪一个更正确Python 有人能给我解释一下从列表中生成集合的两种变体的区别吗?,python,set,Python,Set,我是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= s
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'])
塔克斯 将列表转换为集合不需要for循环:
a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]
print set(a) - set(b)
使用
set
对象而不是set.set()
,set.set()
已被弃用。您也可以通过简单地调用list上的set从列表中创建一个集合<代码>设置([1,2,3])现在是完全不同的:不要对范围内的i(len(a))使用:c.add(a[i])
。按照Python的方式,在a:c.add(value)中为value使用。