As the title mentions, I'm looking for a way for my code to not only detect duplicates in a list, but to separate the items, moving them to other lists.
I am relatively new at programming, having just finished an introductory course to python at my local JC. During the course of the semester, I had an idea to create a program that would read lines in a .txt file, place them in a list, shuffle the list, and split the single list into two new lists before printing them. This would be used for quickly distributing uniquely named objects to two players in a game, for example. Here is what the code looks like so far:
Given that list.txt = apple, apple, banana, pear, orange, kiwi
#create list from text file
list = [line.strip() for line in open("list.txt", 'r')]
#Copy list to preserve the original
list2 = list[::]
random.shuffle(list2) #shuffle the order
#If # of items = odd, remove one
if len(list2) % 2 == 1:
#Divide items into two lists
A = list2[:len(list2)//2]
B = list2[len(list2)//2:]
print("The items in group A are: ", A)
print("The items in group B are: ", B)
unique = set(in_list)
for each in unique:
count = in_list.count(each)
if count > 1:
I'm assuming if you have more than 2 copies of any word, you can ignore everything after the first two. My suggested solution splits the list into repeated values, which will be shared by both groups and single values, which will be shuffled and split among the two groups.
import collections list = ['a', 'a', 'a', 'b', 'b', 'c', 'd'] # Split the list into words that occur once and ones that are repeats single =  repeats =  for word, count in collections.Counter(list).items(): if count > 1: repeats.append(word) else: single.append(word) # Each group gets a copy of the repeats group_a = repeats[:] group_b = repeats[:] # Now shuffle/divide the single values random.shuffle(single) half = len(single) // 2 group_a.extend(single[:half]) group_b.extend(single[half:2*half])
You could add additional shuffles for the individual groups, if you like.