好了,我想/需要使用「|:運營商交集
說我有一個列表:
list = [{1,2,3},{2,3,4},{3,4,5},{4,5,6}]
我需要找到該列表的交集不使用: set.intersection(* L)
理想我想使用的功能有一個for循環(或嵌套的for循環)來獲取返回所有在列表中套的交點:
isIntersction(L) = {1,2,3,4,5,6}
感謝
好了,我想/需要使用「|:運營商交集
說我有一個列表:
list = [{1,2,3},{2,3,4},{3,4,5},{4,5,6}]
我需要找到該列表的交集不使用: set.intersection(* L)
理想我想使用的功能有一個for循環(或嵌套的for循環)來獲取返回所有在列表中套的交點:
isIntersction(L) = {1,2,3,4,5,6}
感謝
試試這個,使用列表理解
list = [{1,2,3},{2,3,4},{3,4,5},{4,5,6}]
b = []
[b.append(x) for c in list for x in c if x not in b]
print b # or set(b)
輸出:
[1, 2, 3, 4, 5, 6]
如果你是熱衷於具有輸出爲一組,試試這個:
b = set([])
[b.add(x) for c in list for x in c if x not in b]
print b
輸出:
set([1, 2, 3, 4, 5, 6]) #or {1, 2, 3, 4, 5, 6}
如果你想有一個函數試試這個:
def Union(L):
b = []
[b.append(x) for c in L for x in c if x not in b]
return set(b)
這正是我正在尋找。我改變了它周圍的長形式: 'DEF一個MyUnion(L): 工會= [] 對於i在L: 對於j在I: 如果我不能用在聯合: union.append(ⅰ) 返回集(union)' –
>>> L=[{1,2,3},{2,3,4},{3,4,5},{4,5,6}]
>>> from itertools import chain
>>> set(chain.from_iterable(L))
{1, 2, 3, 4, 5, 6}
您可以使用內置的reduce
:
>>> L = [{1,2,3},{2,3,4},{3,4,5},{4,5,6}]
>>> reduce(set.union, L, set())
set([1, 2, 3, 4, 5, 6])
這不是路口,這是工會 –
爲什麼你想「理想情況下使用for循環的函數」?你的家庭作業是否說你必須?因爲這樣做沒有什麼「理想」 –
1)是的,這是一個聯盟,我的不好,2,它需要的形式: def isUnion(L): union = {} for我在L: (代碼在這裏) 返回變量 –