Question

I have a tuple of tuples and I want to put the first value in each of the tuples into a set. I thought using map() would be a good way of doing this the only thing is I can't find an easy way to access the first element in the tuple. So for example I have the tuple ((1,), (3,)). I'd like to do something like set(map([0], ((1,), (3,)))) (where [0] is accessing the zeroth element) to get a set with 1 and 3 in it. The only way I can figure to do it is to define a function: def first(t): return t[0]. Is there anyway of doing this in one line without having to declare the function?

Was it helpful?

Solution

Use a list comprehension:

data = ((1,), (3,))
print [x[0] for x in data]

OTHER TIPS

from operator import itemgetter
map(itemgetter(0), ((1,), (3,)))

While the list comprehensions are generally more readable, itemgetter is closest to what he asked for.

Timing information:

>>> from timeit import Timer
>>> mapped = Timer(setup='from operator import itemgetter\nlst=( ("a",), ("b",), (1,), (2,))', stmt='map(itemgetter(0), lst)')
>>> comprehended = Timer(setup='lst=( ("a",), ("b",), (1,), (2,))', stmt='[i[0] for i in lst]')
>>> comprehended.repeat()
[0.5402599483924249, 0.47599876684973275, 0.48340872102501464]
>>> mapped.repeat()
[0.4333492937609478, 0.31100689245737456, 0.3106918944053909]
mySet = set(x[0] for x in TUPLES)

or in python3:

mySet = {x[0] for x in TUPLES}

You can use a set comprehension in Python 2.7 and 3.x:

>>> t = ((1,), (3,))
>>> s = {x[0] for x in t}
>>> s
set([1, 3])

or in Python < 2.7:

>>> s = set([x[0] for x in t])
>>> s
set([1, 3])

Just another way to get it:

set(x for x, in data)
data = ((1,), (3,))
s = set(zip(*data)[0])

If there are more items in your tuples you might save some memory and time using izip and islice.

Python supports the creation of anonymous function using the lambda keyword. This allows you to use a function without formally defining it. Given your example, you'd use the lambda like this:

data = ((1,), (3,))
set(map(lambda x: x[0], data))

This is equivalent to:

def f(x):
    return x[0]

set(map(f, data))

But as other people have said, list comprehensions are preferred over the use of map.

Go with @Winston. List comprehensions are great. If you really want to use map, use a lambda as previously suggested, or the logically equivalent...

from operator import itemgetter
data = ((1,), (3,))
map(itemgetter(0), data)

This is just for info; You should use the list comp

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top