简体   繁体   中英

How do I divide each element in a list by an int using function

I have a dictionary that contains lists as value, and I want to divide each element in those lists on constant, how can I do that using a def function?!

Assuming you're using python and that I got your question, simple way of doing that:

import numpy as np
def divide(input_list, dividend):
  return list(np.array(input_list) / dividend)

You'd probably want to use something like:

CONSTANT_K = 2
dict = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }

for value in dict.values():
    quotientResult = value / CONSTANT_K
    # do whatever you want with the quotient result here

Where CONSTANT_K is your constant. Then, you iterate through your dictionary values in a for loop. The loop takes each value in the dictionary and divides it by the constant. You can handle the values inside of the for loop, or you can store them inside a new dictionary or array.

You can put this into a def function by doing:

CONSTANT_K = 2
dict = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }

def divideDict(k, dictA):
    for value in dict.values():
        quotientResult = value / CONSTANT_K
        # do whatever you want with the quotient result here

divideDict(CONSTANT_K, dict)

Where divideDict() is your function. If you're looking for a dictionary containing lists, you'll have to loop through the lists as well:

CONSTANT_K = 2
dict = { 'a': [1, 2], 'b': [3, 4], 'c': [5, 6], 'd': [7, 8] }

def divideDict(k, dictA):
    for value in dict.values():
        for val in value:
            quotientResult = val / CONSTANT_K
            # do whatever you want with the quotient result here

divideDict(CONSTANT_K, dict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM