logo
Tags down

shadow

Comparing list elements of two lists (with a twist)


By : mukesh shakya
Date : October 18 2020, 06:10 PM
should help you out You can use a list comprehension with zip, and take the abs of the difference between the elements in each tuple:
code :
[abs(i-j) for i,j in zip(l1,l2)]
['{0:.2f}%'.format((min(i,j)/max(i,j))*100) for i,j in zip(l1,l2)]
list(zip(l1,l2))
# [(8, 3), (5, 6), (2, 4), (1, 3)]
l1 = [8,5,2,1]
l2 = [3,6,4,3]

['{0:.2f}%'.format((min(i,j)/max(i,j))*100) for i,j in zip(l1,l2)]
# ['37.50%', '83.33%', '50.00%', '33.33%']


Share : facebook icon twitter icon

Comparing 2 huge lists using C# multiple times (with a twist)


By : Are Jensen
Date : March 29 2020, 07:55 AM
I wish this helpful for you UPDATE
You can do a simple trick - group the prefixes by their first digits into a dictionary and match the numbers only against the correct subset. I tested it with the following two LINQ statements assuming every prefix has at least three digis.
code :
const Int32 minimumPrefixLength = 3;

var groupedPefixes = prefixes
    .GroupBy(p => p.Substring(0, minimumPrefixLength))
    .ToDictionary(g => g.Key, g => g);

var numberPrefixes = numbers
    .Select(n => groupedPefixes[n.Substring(0, minimumPrefixLength)]
        .First(n.StartsWith))
    .ToList();
     MPL    Runtime
    -----------------
     1     10.198 ms
     2      1.179 ms
     3        205 ms
     4        130 ms
     5        107 ms
List<String> prefixes = GeneratePrefixes();
List<String> numbers = GenerateNumbers(prefixes);
var numberPrefixes = numbers.Select(n => prefixes.First(n.StartsWith)).ToList();
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace Test
{
    static class Program
    {
        static void Main()
        {
            // Set number of prefixes and calls to not more than 50 to get results
            // printed to the console.

            Console.Write("Generating prefixes");
            List<String> prefixes = Program.GeneratePrefixes(5, 10, 15);
            Console.WriteLine();

            Console.Write("Generating calls");
            List<Call> calls = Program.GenerateCalls(prefixes, 5, 10, 50);
            Console.WriteLine();

            Console.WriteLine("Processing started.");

            Stopwatch stopwatch = new Stopwatch();

            const Int32 minimumPrefixLength = 5;

            stopwatch.Start();

            var groupedPefixes = prefixes
                .GroupBy(p => p.Substring(0, minimumPrefixLength))
                .ToDictionary(g => g.Key, g => g);

            var result = calls
                .GroupBy(c => groupedPefixes[c.Number.Substring(0, minimumPrefixLength)]
                    .First(c.Number.StartsWith))
                .Select(g => new Call(g.Key, g.Sum(i => i.Duration)))
                .ToList();

            stopwatch.Stop();

            Console.WriteLine("Processing finished.");
            Console.WriteLine(stopwatch.Elapsed);

            if ((prefixes.Count <= 50) && (calls.Count <= 50))
            {
                Console.WriteLine("Prefixes");
                foreach (String prefix in prefixes.OrderBy(p => p))
                {
                    Console.WriteLine(String.Format("  prefix={0}", prefix));
                }

                Console.WriteLine("Calls");
                foreach (Call call in calls.OrderBy(c => c.Number).ThenBy(c => c.Duration))
                {
                    Console.WriteLine(String.Format("  number={0} duration={1}", call.Number, call.Duration));
                }

                Console.WriteLine("Result");
                foreach (Call call in result.OrderBy(c => c.Number))
                {
                    Console.WriteLine(String.Format("  prefix={0} accumulated duration={1}", call.Number, call.Duration));
                }
            }

            Console.ReadLine();
        }

        private static List<String> GeneratePrefixes(Int32 minimumLength, Int32 maximumLength, Int32 count)
        {
            Random random = new Random();
            List<String> prefixes = new List<String>(count);
            StringBuilder stringBuilder = new StringBuilder(maximumLength);

            while (prefixes.Count < count)
            {
                stringBuilder.Length = 0;

                for (int i = 0; i < random.Next(minimumLength, maximumLength + 1); i++)
                {
                    stringBuilder.Append(random.Next(10));
                }

                String prefix = stringBuilder.ToString();

                if (prefixes.Count % 1000 == 0)
                {
                    Console.Write(".");
                }

                if (prefixes.All(p => !p.StartsWith(prefix) && !prefix.StartsWith(p)))
                {
                    prefixes.Add(stringBuilder.ToString());
                }
            }

            return prefixes;
        }

        private static List<Call> GenerateCalls(List<String> prefixes, Int32 minimumLength, Int32 maximumLength, Int32 count)
        {
            Random random = new Random();
            List<Call> calls = new List<Call>(count);
            StringBuilder stringBuilder = new StringBuilder();

            while (calls.Count < count)
            {
                stringBuilder.Length = 0;

                stringBuilder.Append(prefixes[random.Next(prefixes.Count)]);

                for (int i = 0; i < random.Next(minimumLength, maximumLength + 1); i++)
                {
                    stringBuilder.Append(random.Next(10));
                }

                if (calls.Count % 1000 == 0)
                {
                    Console.Write(".");
                }

                calls.Add(new Call(stringBuilder.ToString(), random.Next(1000)));
            }

            return calls;
        }

        private class Call
        {
            public Call (String number, Decimal duration)
            {
                this.Number = number;
                this.Duration = duration;
            }

            public String Number { get; private set; }
            public Decimal Duration { get; private set; }
        }
    }
}

Comparing lists of lists and writing certain elements into a new list


By : Marcos Santos
Date : March 29 2020, 07:55 AM
wish helps you It looks like this question has been asked dozens of times, but none of the answers have helped me out, so I'm afraid I'm asking it again (please don't hate me!). I have two lists of lists:
code :
s = set(x[0] for x in amm)
amv = [x for x in data if x[4] in s]

Comparing elements within list of lists


By : Ajith
Date : March 29 2020, 07:55 AM
around this issue You want to sum up the values at l[4] where key at l[3] is equal. The easiest way to do this is with defaultdict
Example code:
code :
from collections import defaultdict

d = defaultdict(float)

for nested in csv_list:
    d[nested[3]] += nested[4]

new_list = []
for x in d.items():
    new_list.append(list(x))
new_list = [list(x) for x in d.items()]

comparing elements in list of lists


By : user1752924
Date : March 29 2020, 07:55 AM
this will help As you question is a little unclear, try this and check is it ok or not.
code :
bad_list = []
f=''
for i,s in enumerate(l):
    if s[0] == l[i-1][0] or s[0] in bad_list:
        f = f + ' '.join(s[1:])
        bad_list.append(s[0])           
    else:
        f = f + ' '.join(s)
    f = f+ ' ;'
f = [f[:-1] + '.']

Removing sub list by comparing its elements with elements in all other sub lists in Python


By : user2564063
Date : March 29 2020, 07:55 AM
I wish this helpful for you With few adjustments in the initial code and after fixing the bug this code gives the correct output:
code :
lines=[[(x1, y1), (x2, y2), id1, id2],[(x2, y2), (x1, y1), id2, id1]]
for line in lines:
    if [line[1],line[0], line[3],line[2]] in lns: 
         lines.remove([line[1],line[0], line[3],line[2]]) 
Related Posts Related Posts :
  • RegEx for matching specific element of HTML
  • How to initiate widgets through tk/tcl
  • urlparse does not raise exception for an invalid url
  • plot stacked percentage barchart matplotlib
  • How to have the .isupper() and .islower() methods in one line of code?
  • Removing header index from dataframe
  • how to input all data first, then give all output in python?
  • Hot to fix Tensorflow model not running in Eager mode with .fit()?
  • Proxy configuration in Scrapy
  • If/else statement within loop over dataframe
  • I have a code or stop the loop, I do not know how I can do for what stops
  • python pandas : lambda or other method to count NaN values / len(value)<1 along rows
  • Combine two dataframes with same values in several columns
  • Replace Iterations by elegant Pandas code
  • If all elements match requirement not using "if all"
  • Access to 3D array in fragment shader
  • How to normalize the columns of a DataFrame using sklearn.preprocessing.normalize?
  • Validation loss not moving with MLP in Regression
  • ML with imbalanced binary dataset
  • Is there a way to iterate through s3 object content using a SQL expression?
  • Appending lists to a result list keeps replacing the last one appended
  • How can I reuse a function to order different attributes of an object
  • Finding an integer in a list of integers if condition fulfilled
  • Python: Replacing character in for loop
  • Why can I run this command from the terminal but I get an error when my python runs it from the terminal for me?
  • How to create a conda environment from global python environment?
  • PyGame MOUSEBUTTONDOWN event not registering?
  • Pandas - Replace values in column with other values from the same column
  • Why this statement is evaluated to False even it is true?
  • Return an element based on another element in a nested list in python
  • Error ::: ValueError: could not convert string to float: '28,37'
  • How to use for and if together in Python
  • How to call a python method from robot framework
  • Python ThreadPoolExecutor Suppress Exceptions
  • how can solve this problem with dynamic programming?
  • How to convert "tensor" to "numpy" array in tensorflow?
  • Tf 2.0 : RuntimeError: GradientTape.gradient can only be called once on non-persistent tapes
  • Scale and concatenate pandas dataframe into a dask dataframe
  • How to create a URL for templateView?
  • Python : Not getting simple adding result
  • Python hex string encoding
  • Get week start date from week number
  • How to use imports from requirements.txt in python
  • Removing tab indent in ipython shell
  • I need to remove duplicates from a list but add the numeric value in them
  • Delay default arguments being read until function is called
  • Interpolate / fillna with a decay formula in pandas
  • What python package can translate Greek letter to ASCII requivalent?
  • How to get output of OS command from Jupyter notebook?
  • Printing AND writing the RIGHTLY formatted number
  • How do I create a shortcut to import most used python modules?
  • Matplotlib: Show selected date labels on x axis
  • Understanding memoization in Python
  • why does the len function return 2 on some iterations when they are all the same length?
  • Change in preference value does not affect the results of Affinity propagation Clustering
  • returning values inside a function
  • Why cant I use a variable in str slicing?
  • Section divider in Spyder
  • Conditional statement in selenium if element does not exists
  • Pandas : how to select index/row label in dataframe that matches a condition
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk