Python: create frequency table from 2D list - python

Starting with data formatted like this:
data = [[0,1],[2,3],[0,1],[0,2]]
I would like to represent every value once with its frequency:
output = [[[0,1],2],[[2,3],1],[[0,2],1]]
I've found many solutions to this problem for 1D lists, but they don't seem to work for 2D.

It's what that collections.Counter() is for:
>>> from collections import Counter
>>>
>>> Counter(map(tuple,data))
Counter({(0, 1): 2, (2, 3): 1, (0, 2): 1})
>>> Counter(map(tuple,data)).items()
[((0, 1), 2), ((2, 3), 1), ((0, 2), 1)]
Note that since list objects are not hashable you can not use them as the dictionary keys.So you need to convert them to tuple which is a hashable object.

Related

Find an element by inner tuple in a list of a tuple of tuples

Alright. So I've been through some SO answers such as Find an element in a list of tuples in python and they don't seem that specific to my case. And I am getting no idea on how to use them in my issue.
Let us say I have a list of a tuple of tuples; i.e. the list stores several data points each referring to a Cartesian point. Each outer tuple represents the entire data of the point. There is an inner tuple in this tuple which is the point exactly. That is, let us take the point (1,2) and have 5 denoting some meaning to this point. The outer tuple will be ((1,2),5)
Well, it is easy to figure out how to generate this. However, I want to search for an outer tuple based on the value of the inner tuple. That is I wanna do:
for y in range(0, 10):
for x in range(0, 10):
if (x, y) in ###:
print("Found")
or something of this sense. How can this be done?
Based on the suggestion posted as a comment by #timgen, here is some pseudo-sample data.
The list is gonna be
selectPointSet = [((9, 2), 1), ((4, 7), 2), ((7, 3), 0), ((5, 0), 0), ((8, 1), 2)]
So I may wanna iterate through the whole domain of points which ranges from (0,0) to (9,9) and do something if the point is one among those in selectPointSet; i.e. if it is (9, 2), (4, 7), (7, 3), (5, 0) or (8, 1)
Using the data structures that you currently are, you can do it like this:
listTuple = [((1,1),5),((2,3),5)] #dummy list of tuples
for y in range(0, 10):
for x in range(0, 10):
for i in listTuple:#loop through list of tuples
if (x, y) in listTuple[listTuple.index(i)]:#test to see if (x,y) is in the tuple at this index
print(str((x,y)) , "Found")
You can make use of a dictionary.
temp = [((1,2),3),((2,3),4),((6,7),4)]
newDict = {}
# a dictionary with inner tuple as key
for t in temp:
newDict[t[0]] = t[1]
for y in range(0, 10):
for x in range(0, 10):
if newDict.__contains__((x,y)):
print("Found")
I hope this is what you are asking for.
Make a set from the two-element tuples for O(1) lookup.
>>> data = [((1,2),3),((2,3),4),((6,7),4)]
>>> tups = {x[0] for x in data}
Now you can query tups with any tuple you like.
>>> (6, 7) in tups
True
>>> (3, 2) in tups
False
Searching for values from 0 to 9:
>>> from itertools import product
>>> for x, y in product(range(10), range(10)):
... if (x, y) in tups:
... print('found ({}, {})'.format(x, y))
...
found (1, 2)
found (2, 3)
found (6, 7)
If you need to retain information about the third number (and the two-element inner tuples in data are unique) then you can also construct a dictionary instead of a set.
>>> d = dict(data)
>>> d
{(1, 2): 3, (2, 3): 4, (6, 7): 4}
>>> (2, 3) in d
True
>>> d[(2, 3)]
4

Itertools.permutations returns <object> instead of list of permutations

When I input:
import itertools
perm = itertools.permutations(List)
I get:
<itertools.permutations object at 0x03042630>
instead of my permutations list. Could anybody help me to get the actual list that contains all permutations?
It returns an iterator object. If you want to get the actual list, you can easily convert this iterator object in a list using list:
import itertools
l = [1, 2, 3]
perm = list(itertools.permutations(l))
gives you
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
To iterate through the permutations object you have to use a for loop:
import itertools
for permutation in itertools.permutations(L):
print permutation

How to ignore case while doing most_common in Python's collections.Counter?

I'm trying to count the number of occurrences of an element in an iterable using most_common in the collections module.
>>> names = ['Ash', 'ash', 'Aish', 'aish', 'Juicy', 'juicy']
>>> Counter(names).most_common(3)
[('Juicy', 1), ('juicy', 1), ('ash', 1)]
But what I expect is,
[('juicy', 2), ('ash', 2), ('aish', 2)]
Is there a "pythonic" way/trick to incorporate the 'ignore-case' functionality , so that we can get the desired output.
How about mapping it to str.lower?
>>> Counter(map(str.lower, names)).most_common(3)
[('juicy', 2), ('aish', 2), ('ash', 2)]

Get all combinations of list elements not ignoring position in Python

I want to combine all elements of a list into sublists (not tuples) with a specified length.
The itertools.combinations_with_replacement generator does nearly what I want to achieve:
>>> list(itertools.combinations_with_replacement([1,2],2))
[(1, 1), (1, 2), (2, 2)]
There are only two things I dislike: It creates tuples instead of sublists (what I could change with a map), and it misses the element (2,1) in the example above.
Is there any builtin module in Python 2 that does what I want? If not, is there any simple way to at least get combinations_with_replacements (or any other module function) to generate the missing element in the provided example?
maybe:
>>> from itertools import product
>>> list(product([1, 2], repeat=2))
[(1, 1), (1, 2), (2, 1), (2, 2)]

manipulating the output of itertools.permutations in python

I want to take a list, for instance List = [1,2,2], and generate its permutations. I can do this with:
NewList = [list(itertools.permutations(List))]
and the output is:
[[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]]
The Problem: itertools.permutations returns a list of length 1 whose only entry is the list of all permutations of List. That is:
NewList[0] == [(1,2,2),(1,2,2),(2,1,2),(2,2,1),(2,1,2),(2,2,1)]
and
NewList[1] does not exist.
I want the output to be a list where each entry is one of the permutations. That is
NewList[0] == (1,2,2)
NewList[1] == (1,2,2)
NewList[2] == (2,1,2)
...
NewList[5] == (2,2,1)
The Question: Is there a command that will produce the permutations of List in this way? Failing that, is there a way to access the 'individual elements' of [list(itertools.permutations(List))] so I can do things with them?
>>> from itertools import permutations
>>> list(permutations([1,2,2]))
[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]
You don't need to put it in a list again. i.e Don't do [list(permutations(...))] (By doing [] you are making a nested list and hence are unable to access the elements using testList[index], though you could do testList[0][index] but it would be better to just keep it as a list of tuples.)
>>> newList = list(permutations([1, 2, 2]))
>>> newList[0]
(1, 2, 2)
>>> newList[3]
(2, 2, 1)
Now you can access the elements by using their indices.
Why can't you do this:
NewList = [list(itertools.permutations(List))][0]
or even just this:
NewList = list(itertools.permutations(List))
By doing [ list(itertools.permutations(List)) ], you put the list of permutations (the one that you want) inside of another list. So the fix would be to remove the outer []'s

Categories

Resources