+ 2
Replacing repeated numbers with zero
So the idea of the code is to replace 0 in the blist if the same number occurs in mlist. I know how to solve the problem if the list if of the same length. But because the first list length is smaller than the second list. I don’t know how to code it. https://code.sololearn.com/cC4noTfg97zJ/?ref=app
7 Respostas
+ 11
You could cycle through both lists with 2 nested fors. This code will check each item in blist 4 times, using each item in mlist:
for i in range(0, len(mlist)): #Cycles through each item in mlist
for j in range(0, len(blist)): #Cycles through each item in blist
#Check the current item in blist against the current item in mlist
#Replace if same
+ 10
Sorry! Here's the full code:
for i in range(0, len(mlist)):
for j in range(0, len(blist)):
if mlist[i] == blist[j]:
blist[j] = 0
+ 6
I...don't mean to confuse but this works:
print( [x if x not in mlist else 0 for x in blist ] )
I'm happy to break that down (or let someone else take a shot; it's potentially a good learning tool to break it down)
+ 4
Ah, I'm using some things ahead of where you are in the Python lessons I think:
* Lists (and using "in") are covered in section 2, just after "while"
* List comprehensions [ x for x in list ] are in section 5 (More Types)
* The construct: "true value" if condition "false value" is the very last section (Pythonicness...)
When you're ready for those sections, this explanation may help.
# iterates every item in blist, returning a new list:
[x for x in blist]
# Normal "if" statement
if x in mlist:
useValue = 0
else:
useValue = x
...
Shorter way in Python (called ternary in other languages)
"use this value if true" if test_condition else "use this value if false"
useValue = x if x in mlist else 0
So pretending that useValue contains the above test, it looks like this to Python:
[useValue for x in mlist]
Hope that helps you / visitors.
+ 2
@ Kirk. I ran the code and it works. Thanks.
I was taught using while loops. So this is a new one to me.
But thanks tho
+ 2
Thanks. I’ve read everything and it make sense. Really appreciate it
+ 1
@Tamra. Am confused. What goes in the for loops. Thanks.