How to replace values using list comprehension in python3?
问题 I was wondering how would you can replace values of a list using list comprehension. e.g. theList = [[1,2,3],[4,5,6],[7,8,9]] newList = [[1,2,3],[4,5,6],[7,8,9]] for i in range(len(theList)): for j in range(len(theList)): if theList[i][j] % 2 == 0: newList[i][j] = 'hey' I want to know how I could convert this into the list comprehension format. 回答1: You can just do a nested list comprehension: theList = [[1,2,3],[4,5,6],[7,8,9]] [[x if x % 2 else 'hey' for x in sl] for sl in theList] returns