kjooma
kjooma

Reputation: 27

Reformatting string to integer list

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"]

Upvotes: 1

Views: 56

Answers (2)

CoffeeTableEspresso
CoffeeTableEspresso

Reputation: 2652

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.

Upvotes: 1

Beöbe
Beöbe

Reputation: 69

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}

Upvotes: 0

Related Questions