1

I'm trying to compare two lists using set. Problem is my lists are not in the right format. When the lists are compared using set, the result individually breaks down each number instead of each integer.

a = "[1554901200, 1554251400, 1554253200, 1554255000]"
b = "[1554901200, 1554251400, 1554253200]"
print(set(a)& set(b))

>>> set([' ', ',', '1', '0', '3', '2', '5', '4', '9'])

I would like the answer to be:

>>> set([1554901200, 1554251400, 1554253200])

or I would like to find a way to format the list so that set could analyze each rather then

a = ["1554901200", "1554251400", "1554253200", "1554255000"]
6
  • I cannot reproduce the list of characters. This is the output I get set([1554901200, 1554251400, 1554253200]). Commented Mar 29, 2019 at 23:20
  • The second time you write a = ... you have strings, but the first time you have numbers. These will give very different results. which do you have? Commented Mar 29, 2019 at 23:26
  • Sorry the list has been edited Commented Mar 29, 2019 at 23:28
  • @kjooma, After your edit the problem is obvious, see my answer. What you initially wrote is very different from this Commented Mar 29, 2019 at 23:29
  • It's still unclear what OP is asking: starting with two character strings that are the print images of lists, and wanting to finish with lists of ints. I think that OP is still confused. Commented Mar 29, 2019 at 23:40

2 Answers 2

1

Your a and b are strings, so when you make sets out of them, it will make sets out the length 1 strings in them. e.g. set("abc") is a set containing "a", "b", "c". You want:

a = eval("[1554901200, 1554251400, 1554253200, 1554255000]")
b = eval("[1554901200, 1554251400, 1554253200]")

print(set(a)& set(b))

instead. This makes two lists of integers, and makes sets containing the ints in each list, then intersects them.

Make sure that you trust the inputs to eval though.

Sign up to request clarification or add additional context in comments.

2 Comments

I am pulling from google sheets api and I can't change the list by simply taking out the "" around it.
This should do it
0

You need the eval() function:

a = "[1554901200, 1554251400, 1554253200, 1554255000]"
b = "[1554901200, 1554251400, 1554253200]"
print(set(eval(a))& set(eval(b)))

results in

{1554901200, 1554251400, 1554253200}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.