Python Please tell me how to compare different lists and extract only the same values separately... (Wang Beginner)

Asked 2 years ago, Updated 2 years ago, 18 views


number1 = int (input ("get a multiple of the corresponding number: ")))
# For example, suppose you extract a multiple of 3 from 1 to 999.
number2 = int (input ("set multiple to filter once more")
# For example, suppose you take a multiple of 5 from 1 to ~999.

set1 = [] # Where to store a list of multiples of 3 from number1
set2 = [] # Where to save the list of multiples of 5 from number2
for i in range(1,1000):
    if i % number1 == 0:
        set1.append(i)

for i in range(1,1000):
    if i % number2 == 0:
        set2.append(i)

print(set1)
print(set2)

Hello. Simply take two inputs and extract the drainage We're going to learn how to create a list and compare it to get the same value I don't know how to compare the same values between the lists... I think it's a beginner's question, so please tell me how (Crying)

python

2022-09-21 18:55

3 Answers

Hi, how are you?

results = []

for s1 in set1:
    if s1 in set2:
        results.append(s1)

print(results)

I think you can add this code.

To compare between original lists

results = []

for s1 in set1:
    for s2 in set2:
        if s1 == s2:
            results.append(s1)

print(results)

I use it like this a lot, too. However, Python has an ifin grammar that makes it easy to check if the value is in the list.

Have a nice day to day!


2022-09-21 18:55

It's the same thing, but if you express it briefly, you can do it like this. Since you're studying, learn this expression, too!

lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
lst3 = [value for value in lst1 if value in lst2]
print(lst3)


2022-09-21 18:55

The intersection can be obtained as follows.

lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]

set(lst1).intersection(lst2)
{9, 11, 26, 28}


2022-09-21 18:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.