[英]How do I divide each element in a list by an int using function
我有一個包含列表作為值的字典,我想將這些列表中的每個元素划分為常量,我該如何使用 def function 來做到這一點?!
假設您使用的是 python 並且我得到了您的問題,那么簡單的方法是:
import numpy as np
def divide(input_list, dividend):
return list(np.array(input_list) / dividend)
你可能想要使用類似的東西:
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
其中CONSTANT_K
是您的常數。 然后,您在 for 循環中遍歷您的字典值。 循環獲取字典中的每個值並將其除以常數。 您可以在 for 循環中處理值,也可以將它們存儲在新字典或數組中。
您可以通過執行以下操作將其放入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)
其中divideDict()
是您的 function。 如果您正在尋找包含列表的字典,則還必須遍歷列表:
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.