Reputation: 45
I am trying to search through lists within a list to find and change one of the items.
I want to be able to search the 0th and 1st item in the lists, and if they match my criteria I want to change/update the 2nd item.
I understand you can search using enumerate but am struggling to understand/write the coding for this.
myList = [['blue', 'house', 'go', 'no'],['yellow', 'mansion', 'stop', 'yes']]
I would like to be able to search the list for the 0th element being 'blue' and the 1st element being 'house', and then change the 2nd element to 'stop.
Any ideas?
Upvotes: 1
Views: 93
Reputation: 71451
You can use unpacking for a cleaner solution:
myList = [['blue', 'house', 'go', 'no'],['yellow', 'mansion', 'stop', 'yes']]
result = [[*a, 'stop' if a == ['blue', 'house'] else b, c] for *a, b, c in myList]
Output:
[['blue', 'house', 'stop', 'no'], ['yellow', 'mansion', 'stop', 'yes']]
Upvotes: 0
Reputation: 22275
Using a for loop and checking both that the first element of the current inner list equals blue
and the second element equals house
explicitly might be the easiest to understand if you haven't learnt list slicing yet:
my_lists = [['blue', 'house', 'go', 'no'],['yellow', 'mansion', 'stop', 'yes']]
for inner_list in my_lists:
if inner_list[0] == 'blue' and inner_list[1] == 'house':
inner_list[2] = 'stop'
print(my_lists)
Output:
[['blue', 'house', 'stop', 'no'], ['yellow', 'mansion', 'stop', 'yes']]
Upvotes: 1
Reputation: 76297
One-liner using list comprehension
>>> [e if e[: 2] != ['blue', 'house'] else (e[: 2] + ['stop'] + e[3: ]) for e in myList]
[['blue', 'house', 'stop', 'no'], ['yellow', 'mansion', 'stop', 'yes']]
Upvotes: 1
Reputation: 3807
You can slice myList
so you can do both comparisons without using and
myList = [['blue', 'house', 'go', 'no'],['yellow', 'mansion', 'stop', 'yes']]
for m in myList:
if m[:2] == ['blue', 'house']:
m[2] = 'stop'
print(myList)
[['blue', 'house', 'stop', 'no'], ['yellow', 'mansion', 'stop', 'yes']]
Upvotes: 1