python - Mapping Odd/Even to nested lists -
so i'm trying manipulate list loop. changing list string of each integer changing them or odd.
input_list = [[1,2,3], [4,5,6], [7,8,9]]
what have outputted
input_list = [['odd','even','odd'],['even','odd','even'],['odd','even','odd']]
this code wrote far:
for element in input_list: item in element: if item %2==0: input_list[element][x]="even" else: input_list[element][x]="odd" x+=1
any appreciated.
you quite near, smallest change needed program is
input_list=[[1,2,3],[4,5,6],[7,8,9]] i,element in enumerate(input_list): j,item in enumerate(element): if item %2==0: input_list[i][j]="even" else: input_list[i][j]="odd" print input_list
here, i'm using enumerate
instead, because can refer elements in list using indices.
you can using map
, list comprehension
>>> l=[[1,2,3],[4,5,6],[7,8,9]] >>> [list(map(lambda x: 'odd' if x%2 != 0 else 'even',i)) in l] [['odd', 'even', 'odd'], ['even', 'odd', 'even'], ['odd', 'even', 'odd']]
small note - list missing commas, [[1,2,3][4,5,6][7,8,9]]
must [[1,2,3],[4,5,6],[7,8,9]]
another way use logical , operator (&
) in nested list comp, padraic mentions in comments
>>> [['odd' if & 1 else 'even' in sub] sub in l] [['odd', 'even', 'odd'], ['even', 'odd', 'even'], ['odd', 'even', 'odd']]
Comments
Post a Comment