This question already has answers here:
2D List Comprehension to For loop
(3 answers)
Closed 2 years ago.
I want to write the following list comprehension as standard for loop. The List comprehension creates a list of lists that can be printed as matrix.
matrix = [[col for col in range(5)] for row in range(5)]
But I can't get it right to achieve this result:
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
How would the regular for loop look like?
merci A
If you unroll all of those list comprehensions, you get something like
matrix = []
for row in range(5):
line = []
for col in range(5):
line.append(col)
matrix.append(line)
Related
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.
This question already has answers here:
Sum of list of lists; returns sum list
(10 answers)
Closed 1 year ago.
Consider these two lists:
a = [1, 2, 3]
b = [4, 5, 6]
The following line gives me the sum of elements in the same index:
c = [a + b for a, b in zip(a, b)]
Now I have:
[5, 7, 9]
Here is the problem:
my_list = [[1, 0, 1], [-1, 0, 0], ...]
How do I apply list comprehension to sum up a dynamic number of sublists and return a single list like above?
You can use map() with sum() and zip() to achieve this as:
>>> my_list = [[1, 0, 1], [-1, 0, 0], [1, 2, 3]]
>>> list(map(sum, zip(*my_list)))
[1, 2, 4]
OR, you can use zip with a list comprehension as:
>>> [sum(l) for l in zip(*my_list)]
[1, 2, 4]
This question already has answers here:
Why does "x = x.append(...)" not work in a for loop?
(8 answers)
Filter a 2D numpy array
(1 answer)
Closed 1 year ago.
I have matrix like this:
m1 =
[1, 3, 4, 2, 1, 1]
[1, 3, 5, 3, 3, 1]
[1, 2, 3, 1, 1, 0]
[1, 3, 7, 3, 1, 1]
I need to filter it tp get value 1 in the last column. So result should be like this:
filter_array =
[1, 3, 4, 2, 1, 1]
[1, 3, 5, 3, 3, 1]
[1, 3, 7, 3, 1, 1]
My current code is:
m1 = np.array ##see array above
filter_array = [ ] ## the filtered array will be stored here. raw by raw
for raw in m1:
if raw[-1] ==1:
filter_array = filter_array.append(raw[:])
My code gives me back an empty array. I've must missed something...
Simply do this:
filtered = m1[m1[:, -1] == 1]
Note: Your original code did not work because you were assigning the return value of append() method to the filter_array. Since the return value when append to a list is successful is None, you lose your original list after reassigning it to None.
To get your code working, simply do filter_array.append(row[:]) as this mutates the list in place. Simply appending row also works.
filter_array.append(raw[:]) returns nothing. Its NoneType.
So you cannot append row to a NoneType object the second time it executes in the loop.
Your corrected loop should be:
filter_array = []
for raw in m1:
if raw[-1] ==1:
filter_array.append(raw[:])
print(filter_array)
Or better you could use list comprehension and boolean indexing like below:
filter_array = m1[[True if arr[-1] == 1 else False for arr in m1]]
This question already has answers here:
Removing duplicates in lists
(56 answers)
One-liner to remove duplicates, keep ordering of list [duplicate]
(6 answers)
Closed 3 years ago.
I have a big list of strings appearing many times and I want a list of the same strings to appear only once.
An example with numbers would be:
a = [1, 2, 2, 3, 4, 4]
and I want to get
b = [1, 2, 3, 4]
What I tried is something like:
a = [1, 2, 2, 3, 4, 4]
[x for x in a if a.count(x) == 1]
[1, 3]
but this omits the duplicate numbers and takes only those appearing once.
You can try this:
import collections
a = [1, 2, 2, 2, 3, 3, 4, 4, 5, 6, 7, 7, 8]
print([item for item, count in collections.Counter(a).items()])
This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 4 years ago.
I have a list (ex: [1, 2, 2, 3, 4, 3]) and I need to only keep the first occurrence of any of the elements in the list (ex: the list should become [1, 2 ,3, 4]). I know that I could do something like this:
badList = [1, 2, 2, 3, 4, 3]
goodList = []
for element in badList:
if element in goodList:
continue
goodList.append(element)
print (goodList)
However, this is a very messy solution, and I am hoping there is a more elegant way.
from collections import OrderedDict
list(OrderedDict.fromkeys(badList))
[1, 2, 3, 4]
credit to #poke
Just convert to a set then back to a list:
goodList = list(set(badList))