简体   繁体   English

如何使用 function 将列表中的每个元素除以 int

[英]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?!我有一个包含列表作为值的字典,我想将这些列表中的每个元素划分为常量,我该如何使用 def function 来做到这一点?!

Assuming you're using python and that I got your question, simple way of doing that:假设您使用的是 python 并且我得到了您的问题,那么简单的方法是:

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.其中CONSTANT_K是您的常数。 Then, you iterate through your dictionary values in a for loop.然后,您在 for 循环中遍历您的字典值。 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.您可以在 for 循环中处理值,也可以将它们存储在新字典或数组中。

You can put this into a def function by doing:您可以通过执行以下操作将其放入def function 中:

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.其中divideDict()是您的 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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