### 我不明白为什么for循环不起作用

``````def intersect(L1,L2):
tmp = []
for e1 in L1:
for e2 in L2:
if e1 == e2:
tmp.append(e1)
break
result = []
for e in tmp:
if e not in result:
result.append(e)
return result

S = [2,3]
T = [2,3,4]
intersect(S,T)
``````

#### 2 个答案:

Python使用缩进来标记代码块的开始和结束，例如函数或循环体：

``````for condition:
statement_in_loop()
statement_in_loop()

statement_outside_of_loop()
``````

``````def intersect(L1,L2):
tmp = []
for e1 in L1:
for e2 in L2:
if e1 == e2:
tmp.append(e1)
break
result = []
for e in tmp:
if e not in result:
result.append(e)
return result

S = [2,3]
T = [2,3,4]
intersect(S,T)
``````

``````from random import randrange as rr
``````

``````list_length = 10000
random_space = 200000
``````

``````l1 = [rr(0,random_space,1) for i in range(list_length)]
l2 = [rr(0,random_space,1) for i in range(list_length)]
``````

``````def intersect(L1,L2):
tmp = []
checks = 0
for e1 in L1:
for e2 in L2:
checks += 1
if e1 == e2:
tmp.append(e1)
break
result = []
for e in tmp:
if e not in result:
result.append(e)
return result, checks
``````

``````res, checks = intersect(l1, l2)
print(res)
print("Number of comparisons: "+str(checks))
``````

``````def intersect_v2(L1, L2):
dict = {}
checks = 0
for e1 in L1:
checks += 1
dict[e1] = 1
for e2 in L2:
checks += 1
if e2 in dict:
dict[e2] += 1
return [e for e in dict if dict[e] > 1], checks
``````

``````res, checks = intersect_v2(l1, l2)
print(res)
print("Number of comparisons: "+str(checks))
``````