If my list has values that appears more than once I want to do the following:
my_list = ['a','b','c','a','a','b']
I want that my_list becomes ['a','b','c']
and at the same time new_list = ['a','a','b']
I have started with the code but can't manage to finish it:
def func(word):
tgt = 1
found = []
lst = [1,2,3,45,6,1]
if lst.count(word)> 1:
found.append(word)
return found, lst
print(func(1))
CodePudding user response:
You can iterate through the list, store the element in one list if it is not visited or in a new list if it is already visited:
my_list = ['a','b','c','a','a','b']
visited, lst, new_list = set(), [], []
for x in my_list:
if x not in visited:
lst.append(x)
visited.add(x)
else:
new_list.append(x)
print(lst, new_list)
# ['a', 'b', 'c'] ['a', 'a', 'b']
CodePudding user response:
my_list = ['a','b','c','a','a','b']
new_list = my_list.copy()
my_list = list(set(my_list))
my_list.sort()
# remove unique items from new_list
for item in my_list:
new_list.pop(new_list.index(item))
CodePudding user response:
I'm going to use a collections.Counter() to count up the occurrences of each items in the list. At that point the keys() become your new my_list and then we will use some list multiplication to construct your new_list.
import collections
data = ['a','b','c','a','a','b']
counted = collections.Counter(data)
At this point finding your new my_list is dead simple:
my_list = list(counted)
print(my_list)
gives you:
['a', 'b', 'c']
Now we can leverage the fact that ['a'] * 4 == ['a', 'a', 'a', 'a'] to construct a list from they keys of counted based on the number of times they were identified.
new_list = []
for key, value in counted.items():
if value > 1:
new_list.extend([key]*(value-1))
print(new_list)
This will give us back:
['a', 'a', 'b']
Full Solution:
import collections
data = ['a','b','c','a','a','b']
counted = collections.Counter(data)
my_list = list(counted)
new_list = []
for key, value in counted.items():
if value > 1:
new_list.extend([key]*(value-1))
print(my_list, new_list)
CodePudding user response:
lst = ["a","b","a","c","d","b"]
new_list=[]
for i in lst:
if i not in new_list: # check the new list if values repeat or not
new_list.append(i) # add the repeating values in new list
for i in new_list:
if i in lst:
lst.remove(i) # remove the repeating values from first list
print(lst,new_list)
at first you can add the repeating values in a different list then remove these values from your first list.
CodePudding user response:
l = ['a', 'b', 'c', 'a', 'c']
arr = []
for x in l:
if x not in a:
arr.append(x)
# now arr only have the non repeating elements of the array l
