为什么我的代码的最后一部分不起作用?
def common_elements(list1, list2):
#a list with common element
common_elements=[]
common_unique_elements=[]
for i in list1:
if i in list2:
common_elements.append(i)
#removing repeated elements
for i in common_elements:
if i not in common_unique_elements:
common_unique_elements.append(i)
#returning None for empty list
if len(common_elements)==0:
return None
return sorted(common_unique_elements)
答案 0 :(得分:1)
绝对不需要第二个列表来保存唯一的公共元素。您可以在添加到第一个列表之前进行检查,从而避免了第二个列表的需要:
def common_elements(list1, list2):
common = []
for i in list1:
if i in list2 and i not in common:
common.append(i)
return None if not common else sorted(common)
list1 = ['a','b','b,','c']
list2 = ['f','b','e','a','a']
print(common_elements(list1, list2))
# ['a', 'b']
避免对变量使用函数名;以后可能会遇到问题。