0
How to increase plus 2 all elements of lists ?
My code is: m=[[1,2,3], [4,5,6],[7,8,9]] print([r[0] + 2 for r in m] but it will increase only 1 element from every list
6 ответов
+ 6
this can be done with 2 nested loops and an enumerator for the index:
nums = [[1,2,3], [4,5,6],[7,8,9]]
for lst in nums:
for index, num in enumerate(lst):
lst[index] = num +2
print(nums)
# result is: [[3, 4, 5], [6, 7, 8], [9, 10, 11]]
+ 5
m = [[1,2,3], [4,5,6], [7,8,9]]
m = [[*map(lambda el: el+2, el)] for el in m]
print(m)
+ 3
Lothar , thanks. Fixed.
+ 2
m=[[1,2,3],[4,5,6],[7,8,9]]
n=[]
for i in m:
k=[]
for j in i:
k+=[j+2]
n+=[k]
print(n)
+ 2
Thank You all :)
+ 1
Check the performance of different ways of doing it as suggested by people here,
The first one is the code I came up with(similar to one by Vitaly) which is a little expensive
https://code.sololearn.com/c8JJsWQOs0FO/?ref=app
Lastly the best implementation will depend based on large input size but still I just wanted to see how they perform