Array to tuple conversion python [duplicate] - python

This question already has answers here:
Create (L[i], L[i+1]) tuple list from list L [duplicate]
(4 answers)
Closed 7 years ago.
I have an array that looks like this
[1,2,3,4,5]
and I would like a list of tuples that looks like this:
[(1,2),(2,3),(3,4),(4,5)]
What is the most convenient way to do this in python?
Thanks!

zip( a[:-1], a[1:] )
see help(zip) or the website documentation of zip.
Since zip limits itself to the shorter sequence,
zip(a, a[1:])
works too.
EDIT:
Steven brought up the interesting point that if a is very long, doing the implicit copy to get the separate pyObject that is a[1:] is problematic. In this case, you might want to use numpy and its options to get a view on the same data with but a offset.

This can be done using list comprehension and list slicing, you iterate over the elements upto len(a) - 1 and on each iteration slice the elements form current_index and the element next to it.
a = [1,2,3,4,5]
b = [tuple(a[i:i+2]) for i in range(len(a)-1)]
print b
>>> [(1, 2), (2, 3), (3, 4), (4, 5)]

Related

Finding unique list in list of list of tuples [duplicate]

This question already has answers here:
Get unique items from list of lists? [duplicate]
(3 answers)
Closed 2 years ago.
I have a list of lists of tuples:
x = [[(0,0),(0,1)],[(1,2),(2,3)],[(0,0),(0,1)],[(1,2),(2,3)]]
I want all the unique lists present in the list x
My output should be:
x=[[(0,0),(0,1)],[(1,2),(2,3)]]
I tried using x=list(set(x)) but it gives error: 'list is not hashable', I also tried using numpy.unique but it does not give desired output. How can I implement this?
list as mutable and hence can not be used as an element to a set. However, you can type-cast the list to tuple which are immutable, and then you can get unique elements using set. Here I am using map() to covert all sub-lists to tuple:
>>> x = [[(0,0),(0,1)],[(1,2),(2,3)],[(0,0),(0,1)],[(1,2),(2,3)]]
>>> set(map(tuple, x))
{((1, 2), (2, 3)), ((0, 0), (0, 1))}
To type-cast the set back to list and change back nested tuple to list, you can further use map() as:
>>> list(map(list, set(map(tuple, x))))
[[(1, 2), (2, 3)], [(0, 0), (0, 1)]]
i would do something like this:
x = [[(0,0),(0,1)],[(1,2),(2,3)],[(0,0),(0,1)],[(1,2),(2,3)]]
result = []
for i in x:
if not i in result:
result.append(i)
print(result)
maybe it is not the fastest way but certainly it is the simpler.
Otherwise you can use the most "cool" way, you can use sets. Sets are like lists that don't allow equal elements.
x = x = [[(0,0),(0,1)],[(1,2),(2,3)],[(0,0),(0,1)],[(1,2),(2,3)]]
result = list(map(list,set(map(tuple,x))))

How to retrieve an element of a list of enumerated tuples by its enumeration? [duplicate]

This question already has answers here:
Hash Map in Python
(11 answers)
Closed 3 years ago.
I have a list which looks as follows:
vertices = [(1,2),(3,4),(5,6),...]
And I enumerate it using "enumerate":
list(enumerate(vertices))
The list then looks as follows:
[(1,(1,2)),(2,(3,4)),(3,(5,6)),...]
I would like to know if this is the way in python to create a "map" and which is the best way to retrieve a vertex by providing the index. (e.g. providing 1 I would like to receive (1,2), providing 2 I would like to receive (3,4)...)
You can just switch to using the dict constructor instead of list:
d = dict(enumerate(vertices))
which will result:
{0: (1, 2), 1: (3, 4), 2: (5, 6)}
Then you can access the items:
print(d[1])
(3, 4)
Convert it to dict
my_dict = dict([(1,(1,2)),(2,(3,4)),(3,(5,6)),...])
and you can access by index:
my_dict[1]
(1,2)
Almost there:
dict(enumerate(vertices))

Removing coordinates from list on python [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 6 years ago.
I have created a list full of "coordinates" in Python: L1 = [(1,2), (5,6), (-1,-2), (1,-2), etc..].
If I wanted to remove all items in the list which contained negative numbers, how would I do this?
I've tried:
for (a,b) in L1:
if a < 0 or b < 0:
L1.remove(a,b)
But it isn't working. Would very much appreciate any help.
Jack
You cannot change something while you're iterating it. The results are weird and counter-intuitive, and nearly never what you want. In fact, many collections explicitly disallow this (e.g. sets and dicts).
Instead, iterate over a copy (for e in a[:]: ...) or, instead of modifying an existing list, filter it to get a new list containing the items you want ([e for e in a if ...]). Note that in many cases, you don't have to iterate again to filter, just merge the filtering with the generation of the data.
L2 = []
for (a,b) in L1:
if a >= 0 and b >= 0:
L2.append((a,b))
L1 = L2
print L1
You can filter using a list comprehension:
>>> coords = [(1, 2), (5, 6), (-1, -2), (1, -2)]
>>> [coord for coord in coords
... if not any(number < 0 for number in coord)]
[(1, 2), (5, 6)]

Use lists inside a list with itertools.product [duplicate]

This question already has answers here:
Pass a list to a function to act as multiple arguments [duplicate]
(3 answers)
Closed 6 years ago.
I need to calculate the cartesian product of the elements of a few lists. It seems that the best way to do this is to use itertools, and in particular itertools.product. Now, the lists I want to use are themselves contained in a list, and I cannot just use the bigger list for itertools.product. I was wondering how I should extract the lists to make them usable with itertools.product.
Here is an example that shows the problem:
import itertools
elements=[[1, 2], [3, 4]]
product=itertools.product(elements)
print product
This prints [([1, 2],), ([3, 4],)]. What I wanted instead is something equivalent to the following but where I don't have to give all elements of "elements" singularly:
product=itertools.product(elements[0], elements[1])
print product
which prints [(1, 3), (1, 4), (2, 3), (2, 4)].
Thanks.
Unpack the lists in your list with the star operator * to apply the product to your sublists.
product=list(itertools.product(*elements))

search the biggest number of one column in a list of list [duplicate]

This question already has answers here:
Finding max value in the second column of a nested list?
(5 answers)
Closed 10 years ago.
I have an list of list, list = [(1,2,5), (2,8,7),(3,6,9)], and I want to find the biggest number of the third column, so I tried:
zipped = zip(*list)
print max(zipped[2])
But it does not show the biggest number. Anyone know why and a solution?
Works on all newer Pythons:
>>> li = [(1,2,5), (2,8,7),(3,6,9)]
>>> max(l[2] for l in li)
9
If you have text:
>>> li = [('1','2','5'), ('2','8','7'),('3','6','9')]
>>> max(int(l[2]) for l in li)
9
And works even if the source is an iterator / generator. This is on Py3.3 where zip returns an iterator:
>>> gli=(e for e in li)
>>> max(int(l[2]) for l in gli)
9
>>> max(int(l[2]) for l in zip(*li))
9
Works for me on python2.7.
>>> l = [(1,2,5),(2,8,7),(3,6,9)]
>>> zip(*l)
[(1, 2, 3), (2, 8, 6), (5, 7, 9)]
>>> max(zip(*l)[2])
9
Another option:
max(l,key=lambda x:x[2])[2]
or if you prefer itemgetter:
from operator import itemgetter
max(l,key=itemgetter(2))[2]
This is probably more efficient in terms of memory and it'll work on python3.x where zip no longer returns a list.
The key here is that it allows you to get the full tuple that is the biggest (biggest determined by the 3rd element) and then you just pull the correct element out of there if you want it.

Categories

Resources