我试图在列表之间找出独特的元素并避免重复(使用列表理解)
`a = [10 , 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,9]`
`b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]`
dup_list = []
`final_list = [uniq for uniq in a if a not in dup_list if uniq in b ]`
当我尝试将我的dup_list附加在理解语句的最后一行时,它表示无效的语法 即这不起作用。 “final_list = [uniq for uniq in a if a not in dup_list if uniq in b dup_list.append(uniq)” 我是python的新手,所以为任何错过的基本事实道歉。
答案 0 :(得分:0)
a = [10, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 9]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
nodupes = sorted([item for item in a if item not in b] +
[item for item in b if item not in a])
产生[4, 6, 7, 11, 12, 21, 34, 55, 89]
我使用套装的答案相同:
seta = set(a)
setb = set(b)
nodupes = sorted(list(seta ^ setb))