logo
down
shadow

Create list by subtracting the nth+1 value from the nth values of another list


Create list by subtracting the nth+1 value from the nth values of another list

By : Shakila Siddiquea Ti
Date : November 19 2020, 03:01 PM
will help you Using zip and list comprehension:
code :
>>> [ a-b for a,b in zip(mylist[1:], mylist[:-1]) ]
=> [4, 10, 15, 30]
IN : mylist = [1,5,15,30,60]
>>> [ mylist[i+1]-mylist[i] for i in range(len(mylist)-1) ]
=> [4, 10, 15, 30]


Share : facebook icon twitter icon
How can I loop through a list changing the list elements at each time step, adding or subtracting input values that are

How can I loop through a list changing the list elements at each time step, adding or subtracting input values that are


By : hems_smart
Date : March 29 2020, 07:55 AM
I hope this helps . Why don´t I get the following result, in this order? [-2.0, -1.0, 0.0, 1.0, 2.0] [-1.0, 0.0, 1.0, 2.0, 3.0] [-2.0, -1.0, 0.0, 1.0, 2.0], instead i get the second list in the wrong place. Can I edit list elements in a more consistent way, considering this form of input data? My objective is to change a initial list (V) at each time step, adding or subtracting the input values that are in the txt files. , OR:
code :
V = [1,2,3,4,5]

f = open('Qin.txt')     # values in Qin.txt: 1, 3, 2 
fdata = f.readlines()
f.close()

g = open('Qout.txt')    # values in Qout.txt: 4, 5, 5 
gdata = g.readlines()
g.close()

output = [[v + float(x) - float(y) for v in V] for y in gdata for x in fdata]

print output 
>>>  [[-2.0, -1.0, 0.0, 1.0, 2.0], [-1.0, 0.0, 1.0, 2.0, 3.0], [-2.0, -1.0, 0.0, 1.0, 2.0]]
V = [1,2,3,4,5]

f = open('Qin.txt')     # values in Qin.txt: 1, 3, 2 
fdata = map(float, f.readlines())
f.close()

g = open('Qout.txt')    # values in Qout.txt: 4, 5, 5 
gdata = map(float, g.readlines())
g.close()

output = [[v+fdata[i]-y for v in V] for i,y in enumerate(gdata)]
V = [1,2,3,4,5]

f = open('Qin.txt')     # values in Qin.txt: 1, 3, 2 
fdata = map(float, f.readlines())
f.close()

g = open('Qout.txt')    # values in Qout.txt: 4, 5, 5 
gdata = map(float, g.readlines())
g.close()

for i,y in enumerate(gdata):
    for j,v in enumerate(V):
        V[j] = v + fdata[i] - y
    print V
Subtracting values in 2 different list in android

Subtracting values in 2 different list in android


By : Andrew Chan
Date : March 29 2020, 07:55 AM
Hope this helps Answers given by @umair.ali and @Casper are good, converting your arrays to Maps is the way to go.
I would suggest using TreeMap (or other implementation of SortMap interface). TreeMap sorts its keys in ascending order by default. That way, if you really want to have plain array of savings as result, you won't have to do any awkward map sorting after processing.
code :
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class SavingsApp {

    public Map<Integer, Integer> arraysToMap(int[] years, int[] money) {
        Map<Integer, Integer> newMap = new HashMap<Integer, Integer>();
        if (years == null || money == null || years.length != money.length) {
            throw new IllegalArgumentException();
        }
        for (int i=0; i< years.length; i++ ) {
            newMap.put(years[i], money[i]);
        }

        return newMap;
    }

    public Map<Integer, Integer> calculateSavings(Map<Integer, Integer> earningsMap, Map<Integer, Integer>expensesMap) {
        Map<Integer, Integer> savingsMap = new TreeMap<Integer, Integer>();
        savingsMap.putAll(earningsMap);

        for (Entry<Integer, Integer> expensePerYear : expensesMap.entrySet()) {
            Integer year = expensePerYear.getKey();
            Integer expense = expensePerYear.getValue();

            Integer earning = savingsMap.get(year);
            if (earning == null) {
                earning = 0;
            }
            savingsMap.put(year, earning-expense);
        }
        return savingsMap;
    }


    public static void main(String[] args) {
        int[] earningYear = {2012,2013,2014};
        int[] earningAmount = {100,150,120};
        int[] expenseYear = {2012,2014};
        int[] expenseAmount = {50,30};

        SavingsApp app = new SavingsApp();

        // convert arrays to maps
        Map<Integer, Integer> earningsMap = app.arraysToMap(earningYear, earningAmount);
        Map<Integer, Integer> expensesMap = app.arraysToMap(expenseYear, expenseAmount);

        // compute savings per year
        Map<Integer, Integer> savingsMap = app.calculateSavings(earningsMap, expensesMap);

        // convert result map to array
        List<Integer> savingsList = new ArrayList<Integer>(savingsMap.values());
        Integer[] savingsArray = new Integer[savingsList.size()];
        savingsList.toArray(savingsArray);
    }
}
subtracting two values inside a list of list

subtracting two values inside a list of list


By : user3403961
Date : March 29 2020, 07:55 AM
To fix this issue
code :
my_list = [['chr1', 65419, 65433], ['chr1', 65520, 65573], ['chr1', 69037, 71585], ['chr1', 69055, 70108], ['chr1', 137621, 139379],['chr2', 65419, 65433], ['chr2', 65520, 65573], ['chr2', 69037, 71585], ['chr3', 69055, 70108]]
mylist1=list()
mylist2=list()
mylist3=list()

for i in my_list:
    if i[0]=='chr1':
        mylist1.append(i[2]-i[1])
    elif i[0]=='chr2':
        mylist2.append(i[2]-i[1])
    elif i[0]=='chr3':
        mylist3.append(i[2]-i[1])

print("chr1:",sum(mylist1))
print("chr2:",sum(mylist2))
print("chr3:",sum(mylist3))
my_list = [['chr1', 65419, 65433], ['chr1', 65520, 65573], ['chr1', 69037, 71585], ['chr1', 69055, 70108], ['chr1', 137621, 139379],['chr2', 65419, 65433], ['chr2', 65520, 65573], ['chr2', 69037, 71585], ['chr3', 69055, 70108]]
chrset=set()
for i in my_list:
    chrset.add(i[0])

res = dict.fromkeys(chrset, 0)

for i in my_list:
    res[i[0]]=res[i[0]]+i[2]-i[1]
print(res)
create a list of dictionaries from a list of keys and a list of list of values?

create a list of dictionaries from a list of keys and a list of list of values?


By : jeremyrandall
Date : March 29 2020, 07:55 AM
I hope this helps . Given your input and expected output, you can overcome the single nested challenge by using loops. The program can be written as
subtracting values of a list in a dictionary using a dataframe

subtracting values of a list in a dictionary using a dataframe


By : Evandro Saraiva Oliv
Date : March 29 2020, 07:55 AM
around this issue I have a dataframe below, with the products purchased by users. , You can use a dict comprehension:
code :
{k:[e for e in v if e not in df.loc[df.user.eq(k), 'product'].tolist()] for k,v in d.items()}
Out[292]: {'A': [222], 'B': [111], 'C': [], 'D': [], 'G': [222], 'X': [222, 444]}
user_prod = df.groupby('user')['product'].apply(list).to_dict()
{'A': [111],
 'B': [222],
 'C': [111],
 'D': [222],
 'E': [111],
 'F': [222],
 'G': [555],
 'H': [444],
 'I': [333]}
{k:[e for e in v if e not in user_prod.get(k,[])] for k,v in d.items()}
Out[319]: {'A': [222], 'B': [111], 'C': [], 'D': [], 'G': [222], 'X': [222, 444]}
Related Posts Related Posts :
  • How to use an API that requires user's entry (Sentiment Analysis)
  • Django first app
  • Why is this regex code not working
  • Beautifulsoup - findAll not finding string when link is also in container
  • Python: any() to check if attribute in List of Objects matches a list
  • How do I "enrich" every record in a Pandas dataframe with an hour column?
  • Failing to open an Excel file with Python
  • Python function to modify string
  • Pandas DataFrame seems not to have "factorize" method
  • Row column operations in CSV
  • How to decrypt RSA encrypted file (via PHP and OpenSSL) with pyopenssl?
  • How can we use pandas to generate min, max, mean, median, ...as new columns for the dataframe?
  • Cython: creating an array throws "not allowed in a constant expression"
  • Different thing is shown in html
  • sublimetext3 event for program exit
  • Join contigous tokens if the token includes "@" char
  • transparent background in gif using Python Imageio
  • Enable autologin into flask app using active directory
  • Make a NxN array of 1x3 arrays of random numbers (python)
  • django how to use Max and Count on the same field in back-to-back annotations
  • Using the OR operator seems to only take the first of two conditions when used with np.where filter
  • Elegant Dataframe Operations in Pandas
  • Change metadata of pdf file with pypdf2
  • How can I animate a set of points with matplotlib?
  • error: (-215) count >= 0 && (depth == CV_32F || depth == CV_32S) in function arcLength
  • OpenStack KeyStone SSL Exception When Creating an Instance of KeyStone
  • pyspark: The system cannot find the path specified
  • How can I set path to load data from CSV file into PostgreSQL database in Docker container?
  • Summation in python dictionary
  • DRF 3.7.0 removed handling None in fields and broke my foreign key source fields. Is there a way around it?
  • Error with Padlen in signal.filtfilt in Python
  • Abstract matrix multiplication with variables
  • Reading binary data on bit level
  • How to replace multiple instances of a sub strings in a string using a for loop (in a function)?
  • py2neo cypher create several relations to central node in for loop
  • [python-3]TypeError: must be str, not int
  • How to exit/terminate a job earlier and handle the raised exception in apscheduler?
  • python, print intermediate values while loop
  • python to loop over yaml config
  • D3.js is not recognized by PyCharm
  • Access the regularization paths obtained from ElasticNetCV in sklearn
  • Pattern table to Pandas DataFrame
  • Get the earliest date from a column (Python Pandas) after csv.reader
  • Get SystemError: Parent module '' not loaded, cannot perform relative import when trying to import numpy in a Cython Ext
  • Bash or Python : Append and prepend a string recursively in all .tex files
  • Changing a certain index of boolean list of lists change others, too
  • complex dataframe filtering request on the last occurence of a value in Panda/Python [EDIT]
  • How to repeatedly get the contents of a Text widget every loop with tkinter?
  • How to call the tornado.queues message externally
  • How can I use regex in python so that characters not included are disallowed?
  • Discarding randmly scattered empty spaces in pandas data frame
  • Get sums grouped by date by same column filtered by 2 conditions
  • Element disappears when I add an {% include %} tag inside my for loop
  • Django Rest Framework with either a slug or a pk lookup field for the DetailAPIView
  • Flask doesn't stream on Lambda
  • Generate all permutations of fixed length where the elements come from two different sets
  • Making function for calculating distance
  • How to handle multiprocessing based on the limit of CPU's
  • Django - static files is not working
  • Remove x axis and y axis black lines with matplotlib
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org