获取父列表的唯一和重复元素的2个列表

时间:2017-06-26 20:17:14

标签: python python-2.7

我有一个清单:mylist = [1,1,2,3,4,4,5,5,6,6,7,8]:

我想获得2个唯一且重复的元素列表: 重复元素的列表:[1,4,5,6] 独特元素列表:[2,3,7,8]

非常感谢帮助。

3 个答案:

答案 0 :(得分:2)

from collections import Counter
counts = Counter(mylist)
l1 = []
l2 = []
for key in counts:
    if counts[key] > 1:
        l1.append(key)
    else:
        l2.append(key)

这将为您提供两个列表:l1l2,分别包含重复和唯一的元素。

答案 1 :(得分:1)

与@Jason Stein的回答几乎相同,只提供基本功能list(set(mylist)),如果你想upvote请upvote @Jason Stein

mylist=[1,1,2,3,4,4,5,5,6,6,7,8]
L1=[]
L2=[]
for i in list(set(mylist)):
    if mylist.count(i)>1:
        L1.append(i)
    else:
        L2.append(i)

答案 2 :(得分:0)

我这样想:

mylist=[1,1,2,3,4,4,5,5,6,6,7,8]
#case your list is not ordened:
mylist.sort()
duplicated=[]
unique=[]
for i in range(len(mylist)-1):
  if i<len(mylist):
    #comparing the value with the next or the previous in the list:
    if (mylist[i]==mylist[i+1]) or (mylist[i]==mylist[i-1]):
      #if duplicated, add to it's list
      duplicated.append(mylist[i])
    else:
      #if unique, add to it's list
      unique.append(mylist[i])
print("Duplicated: ",list(set(duplicated)))
print("Unique: ",list(set(unique)))

希望帮助了你。