This question already has answers here:
Remove certain consecutive duplicates in list
(6 answers)
Closed 2 years ago.
The post is similar to this but what I want, is to remove specific consecutive duplicate in a list.
So let's say we have this list:
[1,1,1,2,2,3,2,4,4,4,1]
I want to have:
[1,2,2,3,2,4,4,4,1]
I want to remove only the "ones". I am trying itertools.groupby but I haven't found a way to do it.
You could use itertools.groupby and use the grouping key to either keep the key or keep the returned group:
l = [1,1,1,2,2,3,2,4,4,4,1]
from itertools import chain, groupby
list(chain.from_iterable([k] if k==1 else v for k,v in groupby(l)))
# [1, 2, 2, 3, 2, 4, 4, 4, 1]
If you search for ones at the beginning of the list, you do not need to import a module to do this, it is also possible to iterate over the elements in a for-loop:
your_list = [1,1,1,2,2,3,2,4,4,4,1]
for index, element in enumerate(your_list):
if element != 1:
break
if index:
result = your_list[index-1:]
else:
result = your_list
This would check for ones, until it finds another number. The index of the other number -1 is meant to be the beginning of the list.
If there is no 1 in the list, index will be zero and the original list is returned.
Related
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Removing duplicates in lists
(56 answers)
Closed 7 days ago.
I have chosen a slightly different procedure to remove duplicates of a list. I want to keep a new list in parallel, in which each duplicate is added. Afterwards I check if the element is present in the "newly created list" in order to delete it.
The code looks like this:
# nums = [1,1,2] or [0,0,1,1,1,2,2,3,3,4]
t = []
nums_new = nums
for i in nums:
if nums[i] not in t:
t.append(nums[i])
else:
nums_new.remove(nums[i])
nums = nums_new
print(nums)
For the case when nums = [1,1,2] this works fine and returns [1,2].
However, for nums = [0,0,1,1,1,2,2,3,3,4] this case does not seem to work as I get the following output: [0, 1, 2, 2, 3, 3, 4].
Why is this? Can someone explain me the steps?
There are two issues with your code:
Since you are iterating over a list, for i in nums, i is your actual number, not the indexer, so you should just use i instead of nums[i].
nums_new = nums will not actually make a copy of nums, but instead it will make a second binding to the very same list. So you should write nums_new = nums.copy() to avoid changing your original list while you iterate over it.
With those two changes your code works as you wish:
nums = [0,0,1,1,1,2,2,3,3,4]
t = []
nums_new = nums.copy()
for i in nums:
if i not in t:
t.append(i)
else:
nums_new.remove(i)
nums = nums_new
print(nums)
Returns [0,1,2,3,4].
Of course this is an academic exercise of some kind, but note that the Pythonic way to remove duplicates from a list is:
list(dict.fromkeys(nums)) if you want to preserve the order, and
list(set(nums)) for a slightly faster method if you do not care about order.
This question already has answers here:
How to shuffle an array of numbers without two consecutive elements repeating?
(3 answers)
Closed 2 years ago.
I am trying to create a list from multiple repeating elements (type does not really matter as long as they are all the same) in which a given element does not repeat itself back-to-back. Or put differently, there should be no repetitions from index n to index n+1 in the resulting list.
More specifically, I have for example...
shape_typesA = [1, 1, 2, 2]
shape_typesB = [2, 2, 1, 3]
...and I would like to randomly combine them in a list like so:
shape_typesALL = [2, 1, 2, 1, 2, 1, 2, 3]
Each element of each original list (i.e. shape_typesA / shape_typesB) is only allowed to appear once in the resulting list (i.e. shape_typesALL). Lists have typically the same length. If there is no solution, an error should be raised.
What is the best solution for this problem?
from random import shuffle
list = shuffle(list)
def no_repeats_list(old_list):
new_list = []
for i in range(len(old_list) - 1):
if old_list[i] != old_list[i+1]:
new_list.append(old_list[i])
new_list.append(old_list[-1])
return new_list
segregate the items into containers where all items in a container are equal
develop a round robin sequence based on length.
identify length differences of 2 or more from one container to the next in the sequence -- gaps
start with the longest container and remove an item - keep track of list lengths
continue in the sequence removing an item from the next container
use items (out of sequence) from the containers with the least or most number of items to try and maintain length differences of one or less from one container to the next
lists can have duplicate values but sets can not have duplicate values so turn the combined list to a set and afterward turn it back to list.
check out the below code.
shape_typesA = [1, 1, 2, 2]
shape_typesB = [2, 2, 1, 3]
shap = shape_typesA+shape_typesB
shap = set (shap)
shap = list(shap)
print (shap)
In output you will get a list with no repeating characters.
This question already has answers here:
Deleting multiple elements from a list
(32 answers)
Closed 7 years ago.
I have an index of list elements that I want to delete. How can I do that ?
For example, if my original list is a=[1,2,3,4,5,6] and my index list is [2,3]. I want the elements 3,4 to be removed
Since you want to delete the indices, you can do the following two methods:
In place:
for index in sorted(indices, reversed=True):
del a[index]
out of place:
new_a = [el for index, el in enumerate(a) if index not in indices]
The reason why we sort for the in-place version is because deleting from the back doesn't modify the referenced elements in the front (note that this breaks with negative indexing).
a=[1,2,3,4,5,6]
a = a[:2] + a[4:]
print(a)
[1, 2, 5, 6]
This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 8 years ago.
Given a list of n numbers how can i print each element except the duplicates?
d = [1,2,3,4,1,2,5,6,7,4]
For example from this list i want to print : 1,2,3,4,5,6,7
Since order doesn't matter, you can simply do:
>>> print list(set(d))
[1, 2, 3, 4, 5, 6, 7]
It would be helpful to read about sets
If the order does not matter:
print set(d)
If the type matters (want a list?)
print list(set(d))
If the order matters:
def unique(d):
d0 = set()
for i in d:
if not i in d0:
yield i
d0.add(i)
print unique(d)
All you have to do is
create an array.
get list's element.
if element exists in array, leave it.
and if it does not exists, print it.
This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 9 years ago.
I need to access the n and n+1 elements of a list. For example, if my list was [1,2,3,4,5] and my nth element was 2, I'd need the next element in the list, 3.
Specifically, I need to access these elements in order to use them to look up a value in a matrix A
I have a for loop that's iterating over the list:
list = [1,2,3,4,5]
for i in list:
value = A[i,i+1] #access A[1,2], A[2,3], A[3,4], A[4,5]
the problem with this is that I can't do an i+1 operation to access the n+1 element of my list. This is my first time programming in Python and I assumed element access would be the same as in C/C++ but it's not. Any help would be appreciated.
You can use slicing operator like this
A = [1, 2, 3, 4, 5]
for i in range(len(A) - 1):
value = A[i:i+2]
The range function lets you iterate len(A) - 1 times.
Enumerate can give you access to the index of each item:
for i, _ in enumerate(A[:-1]):
value = A[i:i+2]
If all you need are the pairs of data:
for value in zip(A, A[1:]):
value