Domanda

I have 2 sets: one with string values and the other with numeric values.

How can I convert a set of string values into a set of numeric values so that it can can be used with:

set.difference(csv1,csv2)

csv1 = ({92599, 95571, 95382, 95383})

csv2 = ({'92599', '95571', '95382', '95383'})

in to this

csv2 = ({92599, 95571, 95382, 95383})
È stato utile?

Soluzione

Use a set comprehension:

csv2 = {int(n) for n in csv2}

or, for Python versions prior to Python 2.7, use a generator expression:

csv2 = set(int(n) for n in csv2)

Demo:

>>> csv2 = {'92599', '95571', '95382', '95383'}
>>> {int(n) for n in csv2}
set([95571, 95383, 95382, 92599])
>>> set(int(n) for n in csv2)
set([95571, 92599, 95382, 95383])

To create the difference, just call the set.difference() method on csv1 directly:

>>> csv1 = {92599, 95571, 95382, 95383}
>>> csv2 = {int(n) for n in csv2}
>>> csv1.difference(csv2)
set([])

or use the - subtraction operator for the same operation:

>>> csv1 - csv2
set([])

Altri suggerimenti

csv2 = set(int(n) for n in csv2)

is what you want.

Output:

set([92599, 95571, 95382, 95383])
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top