Consider the array a= [1, 2, 3, 1, 2, 3]. Now suppose I want to remove all the 2s in this array in python. So I apply a.remove(2). However the result which comes out is [1, 3, 1, 2, 3], i.e the only first 2 is removed. How can I remove all the 2s which appear in an array? In general, given an array and an element p, how can I remove all the elements of the array which are equal to p?
Edit:- I think I should mention this, this question has been inspired from a Brilliant computer science problem.
Use a list comprehension to build a replacement list, where all elements are not equal to p:
a = [i for i in a if i != p]
Note that in Python, the datatype is called a list, not an array.
You can use filter().
>>> a= [1, 2, 3, 1, 2, 3]
>>> filter(lambda x: x != 2, a)
[1, 3, 1, 3]
In a function :
>>> def removeAll(inList, num):
return filter(lambda elem: elem != num, inList)
>>> removeAll(a, 2)
[1, 3, 1, 3]
Related
lets suppose A = [1, 2, 3, 1, 2, 3, 2, 1, 3, 1, 2, 3].
If B is a subset of A, say [2, 1, 3];
I want to remove B from A in the same order to get [1, 2, 3, 1, 2, 3, 1, 2, 3].
Here's the code I used:
_set = [
1, 2, 3,
1, 2, 3,
2, 1, 3,
1, 2, 3
]
subset = [2, 1, 3]
def remove_subset(_set, subset):
for i in subset:
_set.remove(i)
return _set
print(remove_subset(_set, subset))
But it gives the output [1, 2, 3, 2, 1, 3, 1, 2, 3].
The expected output is: [1, 2, 3, 1, 2, 3, 1, 2, 3].
As written, you're removing the individual elements without paying attention to the order they appear. It looks like you want to delete the elements of the subset only if they appear contiguously in the same order as they do in the subset.
Sadly, this is something Python lists won't do for you (there is no equivalent to str.replace that allows you to remove a fixed sequence wherever it occurs). So you're stuck finding the index where your subsequence occurs and deleting it from the list:
for i in range(len(lst)): # Renamed set to lst, since it is a list, and to avoid shadowing set constructor
if lst[i:i+len(sublst)] == sublst: # Renamed subset to sublst to match
del lst[i:i+len(sublst)] # We found a place where the sublst begins, slice it out
break
This only removes one copy (to avoid issues with mutating a list as you iterate over it, or considering how to handle it if the sublist can overlap itself in the main list).
Side-note: This (iterating over slices of a sequence) is basically the only circumstance in which iterating over sequence indices is the Pythonic solution (there are ways to avoid the unPythonic for i in range(len(lst)): involving enumerate and zip and iter and explicit sequence multiplication and star-unpacking, but they're so ugly it's not worth the bother).
One way could be to convert your lists to strings and use the .replace method of strings -
a = [1, 2, 3, 1, 2, 3, 2, 1, 3, 1, 2, 3]
b = [2, 1, 3]
str_a = ''.join(map(str, a))
str_b = ''.join(map(str, b))
str_a_b_removed = str_a.replace(str_b, '')
list(map(int, list(str_a_b_removed)))
Output
[1, 2, 3, 1, 2, 3, 1, 2, 3]
This question already has an answer here:
flat list as a result of list comprehension [duplicate]
(1 answer)
Closed 12 months ago.
I have a list w where w[i] represents the number of times i should be present in the final result.
For example, if:
w = [1, 3, 4]
then the resulting list should be:
[0, 1, 1, 1, 2, 2, 2, 2]
Notice there is one 0, three 1's, and four 2's.
I have tried to accomplish this with the list comprehension:
w_list = [[i]*w[i] for i in range(len(w))]
but of course this doesn't quite work, giving me this:
[[0], [1, 1, 1], [2, 2, 2, 2]]
How can I write a list comprehension to get me the desired result, like in the example?
You could use a double loop to flatten w_list:
w_list = [x for num, i in enumerate(w) for x in [num] * i]
or
w_list = [x for i in range(len(w)) for x in [i]*w[i]]
Output:
[0, 1, 1, 1, 2, 2, 2, 2]
Here's an alternative solution you might like.
w = [1, 3, 4]
print([i for i in range(len(w)) for _ in range(w[i])])
results in [0, 1, 1, 1, 2, 2, 2, 2] as desired.
Alternatively, [i for i,n in enumerate(w) for _ in range(n)] accomplishes the same thing.
I'm looking to take a list of lists and sort them by an element contained in the contained lists. For clarification, I want to have a list like this code
myList = []
myList.append([1, 2, 3])
myList.append([1, 1, 1])
myList.append([1, 3, 2])
and then sort the elements of list by the last element of each contained list and it would end up looking like this
|
myList = ( v
[1, 2, 3],
[1, 3, 2],
[1, 1, 1])
I also have the numpy library imported in this project. I was looking at argsort for numpy but I don't think you can sort it along an axis of an element
First of all don't use list as variable name as it is one of python built-in function, and second you can use sorted function to sort by position
l = []
l.append([1, 2, 3])
l.append([1, 1, 1])
l.append([1, 3, 2])
sorted(l,key = lambda x : x[2])
#[[1, 1, 1], [1, 3, 2], [1, 2, 3]]
I tried to figure out the following problem through list comprehension but I couldn't make it work. I will show you how I solved the problem using a loop and a list comprehension.
So, I have a list that can have 0 to 6 elements in a range(6) and when I apply my function on it I want to change the values, as shown here:
l = [0, 1, 2, 3, 4, 5]
mirror = [5, 4, 3, 2, 1, 0]
I don't want to just rotate the array by 180 degrees but I actually want to replace the values. For example, my list looks like this now:
l = [2, 5]
Then l_inverted list should look like this:
l_inverted = [3, 0]
I came up with a regular way to solve it but ever since I started learning Python I've preferred list comprehensions.
l = [0, 3, 5]
mirror = [5, 4, 3, 2, 1, 0]
i = 0
for element in l:
l[i] = mirror[element]
i += 1
This actually inverts the l list. Here's my approach using a list comprehension:
l = [3, 5]
mirror = [5, 4, 3, 2, 1, 0]
for element in l:
print(element)
l = [mirror[element] if x==element else x for x in l]
This works fine.
Until:
l = [0, 3, 5]
mirror = [5, 4, 3, 2, 1, 0]
for element in l:
print(element)
l = [mirror[element] if x==element else x for x in l]
So it will replace 5 with 0, 2 with 3 and both 5s (the new one too) become 0. Obviously, I don't want it like that.
Should I stick to the working solution or is there a smooth way to solve it with list comprehensions? I'm trying to practice list comprehensions at all times but it's not fully in my brain yet. Thanks a lot.
If you want it as a list comprehension:
>> l = [0, 3, 5]
>> mirror = [5, 4, 3, 2, 1, 0]
>> l_inverted = [mirror[x] for x in l]
>> l_inverted
[5, 2, 0]
You are drowning in a spoonful of water and trying to take us with you.
You are using bad naming conventions that make your simple problem complicated to comprehend.
orig = [0, 1, 2, 3, 4, 5]
orig_rev = l[::-1]
selector = [0, 3, 5]
result = [orig_rev[i] for i in selector]
print(result ) # [5, 2, 0]
Based on your first two examples, it seems you are looking for the complement of each list value according to some base, similar to ones' complement. You could either hard-code the base as 5 or whatever, or you could assume it's the maximum number in the list and calculate it. Here's a solution for the latter:
Concept
<this complement> = <max value in list> - <this value>
Code
values = [0, 3, 2, 4, 5]
max_value = max(values)
complements = [max_value - value for value in values]
print complements
Result
[5, 2, 3, 1, 0]
I'm fairly new to Python, and besides finding it useful and rather easy to understand for the most part, there are still some things I'm unclear of, ergo this question.
Is it possible to insert specific sections of one list into a specific location in another list?
Say for example, I have a list called 'a', and in this list I have the numbers 1, 3 and 5 in this format:
a = [1, 3, 5]
I also have a list called 'b' which contains the numbers 2 and 4 in this format:
b = [2, 4]
My end goal would be for list 'a' to be changed to this:
a = [1, 2, 3, 4, 5]
As you can see, this would require me to specify using indices for both lists to combine them into one list in this custom format, and I am unsure as to how I could go about this.
I unintentionally left out a major detail, and that is the fact that I wanted to make use of the 'insert' function rather than 'append'.
Yes. Just use insert() and have the second argument be a list element.
a = [1, 3, 5]
b = [2, 4]
# The first argument is the index to insert it at.
# The second is the actual item to be inserted.
a.insert(1, b[0]) # [1, 2, 3, 5]
a.insert(3, b[1]) # [1, 2, 3, 4, 5]
Note that if you just want a sorted, you can just use this:
for item in b:
a.append(item) # Order does not matter, we will sort it later
# a is currently [1, 3, 5, 2, 4] since append() adds to the end of the list
a.sort()
# a is now [1, 2, 3, 4, 5] as sort() re-ordered it
Or if you want it even simpler, concatenate them and then sort:
a = a + b # [1, 3, 5, 2, 4]
a.sort() # [1, 2, 3, 4, 5]
Let me know if this is unclear or not what you wanted.
How does this work for you?
a = [1,2,5,6,7]
b = [3,4]
for n,k in enumerate(a):
if(k<b[0]):
a = a[0:n]+b+a[n:]
break
print(a)
using the colon to slice arrays is super useful.
If you're interleaving the lists, you can zip them using izip_longest:
>>> a = [1, 3, 5]
>>> b = [2, 4]
>>> from itertools import izip_longest
>>> [c for pair in izip_longest(a, b)
... for c in pair if c is not None]
[1, 2, 3, 4, 5]