I have two lists, let's say:
l1 = ['c', 'o', 'k', 'e']
l2 = ['a', 'b', 'c', 'd']
I would like to create a loop, that would check if each letter in l1 is in l2 (if that's the case I would get " ") or if it's there and on the same position (in that case I would get "Y").
I started with this code (unfortunately I failed). Could you please advise what's missing?
for i in l1:
for j in range(0,4):
if l1[j] == l2[j]:
v = "Y"
elif i in l2:
v = "."
else:
v = "N"
text = "".join(v)
Which those lists in the example, I would assume to get:
text = .NNN
I understand that this might be an easy question, but I'm a beginner and it's driving me crazy :)
CodePudding user response:
Looking at your code, you can use zip()
to iterate over the two lists simultaneously. Also use str.join
after the loop:
l1 = ["c", "o", "k", "e"]
l2 = ["a", "b", "c", "d"]
out = []
for a, b in zip(l1, l2):
if a == b:
out.append("Y")
elif a in l2:
out.append(".")
else:
out.append("N")
print("".join(out))
Prints:
.NNN
CodePudding user response:
l1 = ['c', 'o', 'k', 'e']
l2 = ['a', 'b', 'c', 'd']
text = ""
for i in l1:
if i in l2:
v = "."
else:
v = "N"
text = v
print(text)
First we define text=""
so that we can just append. Then we loop all the letters in l1
. We then check if that letter is in l2
. if it is we add '.'
to text
if its not we add N
. And finally we print the text
CodePudding user response:
You can do something like:
ans = ""
for i, val in enumerate(l1):
if l2[i] == val:
ans = "Y"
elif val in l2:
ans = "."
else
ans = "N"
CodePudding user response:
You don't have to loop trough the second array with the operations you are performing. You can simplify your code like this.
l1 = ['c', 'o', 'k', 'e']
l2 = ['a', 'b', 'c', 'd']
text = ""
for i in range(len(l1)):
if l1[i] == l2[i]:
text = "Y"
elif l1[i] in l2:
text = "."
else:
text = "N"
print(text)
Looping twice is not needed and therefore not the most efficient solution to your problem.
CodePudding user response:
Use python sets.
Simple ./N check
l1 = ['c', 'o', 'k', 'e']
l2 = ['a', 'b', 'c', 'd']
S = set(l2)
out = ''.join('.' if x in S else 'N' for x in l1)
output: .NNN
more complex ./Y/N check:
l1 = ['c', 'o', 'k', 'e', 'z']
l2 = ['a', 'b', 'c', 'd', 'z']
S = set(l2)
out = ''.join(('Y' if l2[i]==x else '.') if x in S else 'N'
for i, x in enumerate(l1))
output: .NNNY
CodePudding user response:
l1 = ['c', 'o', 'k', 'e']
l2 = ['a', 'b', 'c', 'd']
text = ""
for char in l1:
if char in l2:
index = l1.index(char)
if char == l2[index]:
v = "Y"
else:
v = "."
else:
v = "N"
text = v
print(text)