So my problem, to which I have been searching a solution for hours now, is, that I have a list of list with lists of various lengths and different items:
list_1=[[160,137,99,81,78,60],[132,131,131,127,124,123],'none',[99,95,80,78]]
Now I want to change the fifth number of every list and add 1. My problem is, that I keep getting 'out of range' or other problems, because list 3 doesn't contain numbers and list 3 4 don't contain a fifth element.
I have so far found no answer to this. My first guess was adding zeros to the lists, but I'm not supposed to do that. It would also falsify the results, since then it would add 1 to any zero I have created.
CodePudding user response:
Try to fix the previous post, and make minor correction, try it and ask any questions:
Any function should return the modified list, otherwise, you will not get it (unless it's supposed to do in-place changes)
You may try do List Comprehension as well, but that's more involved.
L =[[160,137,99,81,78,60],[132,131,131,127,124,123], None,[99,95,80,78]]
def addOne(L):
for lst in L:
if isinstance(lst, list) and len(lst) >= 5:
lst[4] = 1
return L
print(addOne(L))
Output:
[[160, 137, 99, 81, 79, 60], [132, 131, 131, 127, 125, 123], None, [99, 95, 80, 78]]
CodePudding user response:
Assuming this is in Python,
list_1=[[160,137,99,81,78,60],[132,131,131,127,124,123],'none',[99,95,80,78]]
def addOneToFifthElement(theList):
for list_ in theList:
if type(list_)=="<class 'list'>" and len(list_)>=5:
list_[4] = 1
addOneToFifthElement(list_1)