I have 2 lists, for example:
JavaScript
x
3
1
list1 = [1, 2, 2, 3, 3, 4]
2
list2 = [1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5]
3
I want to get a list 3 which will include all numbers from list2 matching the numbers from list1:
JavaScript
1
2
1
list3 = [1, 1, 2, 2, 3, 3, 4, 4, 4]
2
I was trying to use 2 while loops to go through list1 and list2 and match numbers, but it gives me wrong number of values:
JavaScript
1
16
16
1
listO = [1, 2, 2, 3, 3, 4]
2
listX = [1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5]
3
x_temp = []
4
a = 0
5
b = 0
6
7
while a < len(listO):
8
while b < len(listX):
9
if listO[a] == listX[b]:
10
x_temp.append(listX[b])
11
print("Outlier a:" , listO[a] )
12
listX.remove(listX[b])
13
b+=1
14
b=0
15
a+=1
16
list3 = [1, 2, 2, 3, 3, 4, 4]
Is there any way to do it using loops?
- Please do NOT provide solution using set() it doesn`t work for my lists!
Advertisement
Answer
With a for loop:
JavaScript
1
10
10
1
listO = [1, 2, 2, 3, 3, 4]
2
listX = [1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5]
3
x_temp = []
4
5
for x in listX:
6
if x in listO:
7
x_temp.append(x)
8
9
# [1, 1, 2, 2, 3, 3, 4, 4, 4]
10