logo
Tags down

shadow

Python3 - how can I sort the list by frequency of its elements?


By : user2175306
Date : October 15 2020, 08:10 PM
To fix this issue You can use a itertools.Counter for your sorting in different ways:
code :
from collections import Counter

lst = ['Hi', 'beautiful', 'creature', 'Said', 'by', 'Rothchild', 'the', 'biggest', 'enemy', 'of', 'Zun', 'Zun', 'started', 'get', 'afraid', 'of', 'him', 'As', 'her', 'best', 'friend', 'Lia', 'can', 'feel', 'her', 'fear', 'Why', 'the', 'the', 'hell', 'you', 'are', 'here']

c = Counter(lst)  # mapping: {item: frequency}

# now you can use the counter directly via most_common (1.)
lst = [x for x, _ in c.most_common()]
# or as a sort key (2.)
lst = sorted(set(lst), key=c.get, reverse=True)

# ['the', 'Zun', 'of', 'her', 'Hi', 'hell', 'him', 'friend', 'Lia', 
#  'get', 'afraid', 'Rothchild', 'started', 'by', 'can', 'Why', 'fear', 
#  'you', 'are', 'biggest', 'enemy', 'Said', 'beautiful', 'here', 
#  'best', 'creature', 'As', 'feel']
from collections import OrderedDict

lst = sorted(OrderedDict.fromkeys(lst), key=c.get, reverse=True)

# ['the', 'of', 'Zun', 'her', 'Hi', 'beautiful', 'creature', 'Said', 
# 'by', 'Rothchild', 'biggest', 'enemy', 'started', 'get', 'afraid', 
# 'him', 'As', 'best', 'friend', 'Lia', 'can', 'feel', 'fear', 'Why',  
# 'hell', 'you', 'are', 'here']


Share : facebook icon twitter icon

In python, how to sort list by frequency of elements


By : Jason Chung
Date : March 29 2020, 07:55 AM
hop of those help? I have a list of elements: [ 3, 3, 6, 6, 6, 5, 5, 8 ] and need to sort it by the frequency of elements to get this: [ 6, 6, 6, 3, 3, 5, 5, 8 ] of several elements have the same frequency sort them by value. Can you find any shorter way than this? , Try this
code :
>>> old_list = [ 3, 3, 6, 6, 6, 5, 5, 8 ]
new_list = sorted(old_list, key = old_list.count, reverse=True)
>>> new_list
[6, 6, 6, 3, 3, 5, 5, 8]

How to count the frequency of elements in a unsorted string-list in Python3?


By : Yacine O
Date : March 29 2020, 07:55 AM
Any of those help Use collections.Counter.
code :
>>> from collections import Counter
>>> l = ['banana', 'apple', 'linux', 'pie', 'banana', 'win', 'apple', 'banana']
>>> Counter(l)
Counter({'banana': 3, 'apple': 2, 'pie': 1, 'win': 1, 'linux': 1})

Sort the array elements based on the elements frequency in java


By : Anthony Bonafide
Date : March 29 2020, 07:55 AM
Hope that helps I'm just curious why couldn't you use the good old bubble sort in the case and just customize a bit the Bubble In worst case scenario the time complexity is going to be O(n*n) and space complexity will be O(3n) :)
Pure arrays implementation is going to be something like:
code :
private static void bubbleSortByOccurrences(int[] arr) {
    int[][] counter = new int[2][arr.length];
    int counterIndex = -1;

    for (int value : arr) {
        int idx = 0;
        for (; idx <= counterIndex; idx++) {
            if (counter[0][idx] == value) {
                counter[1][idx]++;

                while (idx > 0 && counter[1][idx] > counter[1][idx-1]) {
                    int temp = counter[1][idx];
                    counter[0][idx] = counter[0][idx-1];
                    counter[1][idx] = counter[1][idx-1];
                    counter[0][idx-1] = value;
                    counter[1][idx-1] = temp;
                    idx--;
                }
                break;
            }
        }

        if (idx > counterIndex) {
            counter[0][idx] = value;
            counter[1][idx]++;
            counterIndex = idx;
        }
    }

    fillArrayBackwards(arr, counter, counterIndex);
}

private static void fillArrayBackwards(int[] buf, int[][] counter, int counterIndex) {
    for (int i = counterIndex, j = buf.length - 1; i >=0; i--) {
        for (int k = 0; k < counter[1][i]; k++) {
            buf[j--] = counter[0][i];
        }
    }
}
private static void bubbleSortByOccurrences(int[] arr) {
    Bubble head = null;

    for (int value : arr) {
        if (head == null) {
            head = new Bubble(value);
        } else {
            Bubble currentHead = null;
            Bubble current = head;

            for (; current != null && !(current.getValue() == value); current = current.getTail()) {
                currentHead = current;
            }

            if (current == null) {
                current = new Bubble(value);
                current.setTail(head);
                head = current;
            } else {
                current.incrementOccurrences();

                while (current.getTail() != null && current.getOccurrences() > current.getTail().getOccurrences()) {
                    Bubble currentTail = current.getTail();
                    current.setTail(currentTail.getTail());
                    currentTail.setTail(current);

                    if (currentHead != null) {
                        currentHead.setTail(currentTail);
                        currentHead = currentTail;
                    } else {
                        head = currentTail;
                    }
                }
            }
        }
    }

    fillArrayBackwards(arr, head);
}

private static void fillArrayBackwards(int[] buf, Bubble head) {
    int i = buf.length - 1;
    for (Bubble current = head; current != null; current = current.getTail()) {
        for (int j = 0; j < current.getOccurrences(); j++) {
            buf[i--] = current.getValue();
        }
    }
}
class Bubble {
    private int value;
    private int occurrences;
    private Bubble tail;

    public Bubble(int value) {
        this.value = value;
        this.occurrences = 1;
    }

    public int getValue() {
        return value;
    }

    public int getOccurrences() {
        return occurrences;
    }

    public void incrementOccurrences() {
        this.occurrences++;
    }

    public Bubble getTail() {
        return tail;
    }

    public void setTail(Bubble tail) {
        this.tail = tail;
    }
}

Whats the most efficient way to sort elements of an array based on frequency of elements


By : user3603017
Date : March 29 2020, 07:55 AM
will help you You could create a list from the map's entrySet and then sort the list using a custom comparator which compares based on the values of the map.
Creating a List from the Map's entrySet - use the constructor which takes another collection as an argument. Sorting the list - Collections.sort using a Comparator implementation.

Count frequency of words in a list and sort by frequency


By : onsitesigns
Date : March 29 2020, 07:55 AM
like below fixes the issue I am using Python 3.3 , use this
Related Posts Related Posts :
  • i need to click unordered links in the below URL using selenium, python
  • How to join pandas dataframe with itself?
  • How to apply a color cast to a video frame in OpenCV Python?
  • Is there any existing library for median filtering with kernel size greater then 5 using OpenCL acceleration in python?
  • Changing the color of points in scatter plot for different dummy values
  • Calculate center for each polygon in a list efficiently
  • Loading modules in the same Python package
  • replacing pixels in an imagewith pixels from another image python
  • Suggestion on picking the best options of two lists (minimum and maximum )python
  • Resetting Index in a Dataframe drops the Indexed column by 1 row
  • Convert number which are str from readlines to digits - python
  • Unable to authenitcate with python minds api
  • Print variables from a query in python
  • Ipython does not see the installed library
  • Javascript-like array-method chaining in Python?
  • PyQT: Get contents CustFormWidgetIem inside QListWidgetItem
  • Bottle server: HTTPResponse vs bottle.response
  • pytorch vgg model test on one image
  • Runtime scope and `main` symbol is different inside or outside a function
  • Use anaconda in pycharm (Import libraries error, updating anaconda and virtual environment)
  • how to get the sum of a CSV column list to print
  • Python plot drop lines with repeating value in column
  • receive binary file from POST request with BaseHTTPRequestHandler
  • D-Bus - 'ServiceUnknown' exception encountered while calling a remote procedure
  • Pandas .min() method doesn't seem fastest
  • Pandas: How to reference columns of structure: ('Name', n) ('Name', n+1)
  • Read a text file and remove all characters except alphabets & spaces in Python
  • Compute all powerset intersections of two lists
  • Applying literal_eval on string of lists of POS tags gives ValueError
  • Modelling a logic puzzle
  • What is the meaning of Copy_X in sklearn linear models
  • selenium.common.exceptions.ElementNotInteractableException: Message: Element is not displayed
  • pydev debugger does not stop in breakpoint
  • Python windows path regex
  • Flask and selenium-hub are not communicating when dockerised
  • How to use groupby on a single column and perform comparisons for multiple columns in Pandas?
  • Locate a python script without absolute path
  • Custom-formatted Django form errors appearing twice
  • Matploblib: Paint cells of matrix based on indexes stored in array
  • How to repeat a drawing horizontally in pygame (drawing done in a class method)?
  • How to convert numpy array from numpy.int64 to datetime?
  • How do I pad values in the array so that I get this?
  • Numpy generate random whole number
  • How to find Price Tag with Dollar Sign, thousand delimiter AND decimal point by Python Regex
  • Python Scikit - bad input shape when calling sklearn.metrics.precision_recall_curve
  • struggle to understand tkinter multi classes
  • Wait for Button to be pressed after selecting Radiobutton then run command (Tkinter)
  • BeautifulSoup find() returns tags, but no value between the tags. Why is this?
  • Approximation of F using Hooke's Law
  • suggestion on filtering lists items that corresponds to other lists
  • Sort a list using a partial match in another list
  • Can filter() contain two conditions?
  • Kivy popup button content doesn't show in the button
  • Python - masking in a for loop?
  • Find which term is repeated in a string, when given a known number of N occurrences in the string
  • Replace all elements in list Python
  • How can I speed up my MySQL (InnoDB) inserts?
  • Can I input a Byte Tensor to my RNN/LSTM model?
  • Autoincrement file names
  • Problems transforming data in a dataframe
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org