python - replace values in list depending on value of current item and next item -
i trying use python code below output new list. output of print (words) should ['my','name','is','michael','apples','i','like','cars']
.
right now, print (words)
outputs ['cars']
. missing here?
a = 'my name michael , cars' b = a.split() words = none i, j in enumerate(b): words = [] if j == "and" , b[i+1][0] == "i": words.append("apples") else: words.append(j) print (words)
create words
outside loop, see last word because keep setting words equal empty list each iteration:
words = [] # outside loop i, j in enumerate(b):
if and
happens last word indexerror
. can set start index 1
in enumerate don't need +1 , avoid potential error indexing:
words = [] i, j in enumerate(b, 1): if j == "and" , b[i][0] == "i":
you can put in list comprehension:
a = 'my name michael , cars' b = a.split() words = ["apples" if wrd == "and" , b[i][0] == "i" else wrd i, wrd in enumerate(b,1)] print(words) ['my', 'name', 'is', 'michael', 'apples', 'like', 'cars']
you can avoid indexing using iter
, next
:
a = 'my name michael , cars' = iter(a.split()) words = ["apples" if wrd == "and" , next(it," ")[0] == "i" else wrd wrd in ] print(words) ['my', 'name', 'is', 'michael', 'apples', 'like', 'cars']
Comments
Post a Comment