Finding and replacing elements in a list
You can use the built-in enumerate
to get both index and value while iterating the list. Then, use the value to test for a condition and the index to replace that value in the original list:
>>> a = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1]
>>> for i, n in enumerate(a):
... if n == 1:
... a[i] = 10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]
Replace elements in lists based on indexes python
Try this:
rest=[5, 7, 11, 4]
b=[21, 22, 33, 31, 23, 15, 19, 13, 6]
last=[33, 19, 40, 21, 31, 22, 6, 15, 13, 23]
for i, l in enumerate(last):
if l in b:
if b.index(l) < len(rest):
last[i] = rest[b.index(l)]
print(last)
Finding an element in nested python list and then replacing it
Using numpy
:
NL = np.array(NL)
mask = np.where(NL == 5)
NL[mask] = 10
array([[ 1, 2, 3],
[ 4, 10, 6],
[ 7, 8, 9]])
Solution2:
def get_index(num, List):
for row, i in enumerate(List):
if num in i:
return row, i.index(num)
return -1
idx = get_index(5,NL)
if idx>0:
NL[idx[0]][idx[1]] = 7
[[1, 2, 3], [4, 7, 6], [7, 8, 9]]
How to replace elements in python list by values from dictionary if list-element = dict-key?
Use dict.get
inside a list comprehension:
lst = ["yellow", "red", "green", "blue"]
dic = {"green":"go", "yellow":"attention", "red":"stay"}
res = [dic.get(e, e) for e in lst]
print(res)
Output
['attention', 'stay', 'go', 'blue']
Having trouble replacing elements in a 2d list with a 1d list using for-loops
Here are some comments on your code and examples of how to make it do what the question describes:
(1.) References vs copies: list1 = [[0]*4]*10
creates a single 4-element list and populates list1
with 10 references to it (NOT 10 copies of it).
For an example of what this implies, watch this:
list1 = [[0]*4]*10
list1[1][0] = 33
list1[1][1] = 39
list1[1][2] = 45
list1[1][3] = 51
print(list1)
... gives this:
[[33, 39, 45, 51], [33, 39, 45, 51], [33, 39, 45, 51], [33, 39, 45, 51], [33, 39, 45, 51], [33, 39, 45, 51], [33, 39, 45, 51], [33, 39, 45, 51], [33, 39, 45, 51], [33, 39, 45, 51]]
In other words, updating one list element within list1
updates them all, since each element of list1
is just a reference to the same list.
If this is not what you want, you can use list1 = [[0]*4 for _ in range(10)]
instead to give you a distinct list (10 in total) for each index in list1
:
list1 = [[0]*4 for _ in range(10)]
list1[1][0] = 33
list1[1][1] = 39
list1[1][2] = 45
list1[1][3] = 51
print(list1)
... gives:
[[0, 0, 0, 0], [33, 39, 45, 51], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Your code as written would tend to imply that the second approach above is what is needed.
(2.) Code fix assuming nested lists cannot be replaced: It's unclear from the question whether whether you are allowed to replace each list in list1
to get the desired values, or if you are expected to leave the nested lists in place and simply modify their numerical contents.
If list replacement is not allowed, then your code can be rewritten like this:
list1 = [[0]*4 for _ in range(10)]
list2 = [11,13,15,17]
list1[0][:] = list2
for i in range(9):
for j in range(4):
list1[i + 1][j] = list2[j]*(3**(i + 1))
print(list1)
... giving:
[[11, 13, 15, 17], [33, 39, 45, 51], [99, 117, 135, 153], [297, 351, 405, 459], [891, 1053, 1215, 1377], [2673, 3159, 3645, 4131], [8019, 9477, 10935, 12393], [24057, 28431, 32805, 37179], [72171, 85293, 98415, 111537], [216513, 255879, 295245, 334611]]
Note that these changes were made to your code:
- Changed the initialization of
list1
to allocate 10 distinct nested lists. - Eliminated
i = 1
(not needed because thefor
loop takes care of initializingi
),j = 0
(similar reason),j+=1
(not needed because thefor
loop takes care of updatingj
) andi+=1
(similar reason). - Changed
list1[i][j]
tolist1[i + 1][j]
to fix the indexing. - Changed
3**i
to3**(i + 1)
to calculate the correct multiplier.
(3.) Code fix assuming nested lists can be replaced: In this case, your looping logic can be simplified and you don't need to use nested lists when initializing list1
.
Here is a long-hand way to do what you ask which will overwrite the contents of list1
with new nested lists that have the desired values:
list1 = [None] * 10
list2 = [11,13,15,17]
list1[0] = list2
mul = 3
for i in range(1, len(list1)):
temp = [0] * len(list2)
for j in range(len(list2)):
temp[j] = mul * list2[j]
list1[i] = temp
mul *= 3
print(list1)
Here is a way that uses a list comprehension inside a loop:
list1 = [None] * 10
list2 = [11,13,15,17]
list1[0] = list2
mul = 3
for i in range(1, len(list1)):
list1[i] = [mul * v for v in list2]
mul *= 3
print(list1)
And finally, here is a very compact nested list comprehension approach:
list1 = [None] * 10
list2 = [11,13,15,17]
list1 = [[(3 ** i) * v for v in list2] for i in range(len(list1))]
Related Topics
Python Dictionary Comprehension
How to Improve Performance of This Code
How to Explicitly Free Memory in Python
What Is the Eafp Principle in Python
How to Pad a String With Zeroes
How to Sort a List of Objects Based on an Attribute of the Objects
All Combinations of a List of Lists
C Function Called from Python Via Ctypes Returns Incorrect Value
Why Is _Init_() Always Called After _New_()
How to Get Line Count of a Large File Cheaply in Python
Best Way to Convert String to Bytes in Python 3
How to Connect to a MySQL Database in Python
Changing the "Tick Frequency" on X or Y Axis in Matplotlib
How to Call a Script from Another Script
How Does Assignment Work With List Slices