python - 如何用Python中字典中的值替换函数变量
问题描述
我正在尝试遍历下面的字典并将函数内的“字符串”变量替换为字典中的值,然后执行该函数。我正在考虑编写一个 for 循环,然后将函数包含在 for 循环中。请帮忙。
预期功能:
def my_function(fname): string = value print(string + " Refsnes") my_function("string")
dict = {"kafka":[{
"value":"I am"},
{"value":"You are"},
{"value":"They are"}
]}
def my_function(fname):
string = "I am"
print(string + " Refsnes")
my_function("string")
解决方案
最好的办法是首先修改你的字典。现在“kafka”映射到所有具有相同密钥的字典列表,那么为什么要首先打扰并拥有一个密钥。所以你可以有一个像这样的字典:
dictionary = {"kafka": ["I am", "You are", "They are"]}
也不要调用变量dict
,因为你会覆盖内置函数dict
,使其无法使用。
然后,您还必须更改函数以实际使用该参数。
def my_function(string):
print(string + " Refsnes")
现在,要遍历 dict 并打印具有所有值的函数,您有两个选项。
首先循环遍历字典中的列表并重复调用该函数:
for string in dictionary["kafka"]:
my_function(string)
或者给你的函数一个列表,然后循环遍历函数中的列表。您的函数将如下所示:
def my_function(list_of_strings):
for string in list_of_strings:
print(string + " Refsnes")
# Call function with
my_function(dictionary["kafka"])
推荐阅读
- machine-learning - Gensim 快速文本获取词汇或单词索引
- c++ - 编写 C++ 程序以使用 ITERATION 查找数字的倒数
- jquery - 如何从选择中搜索/过滤特定的 DataTables 列
- amazon-web-services - AWS route53裸域A记录
- android - 没有滚动内容时如何下拉协调器布局
- python - Python sklearn dcg_score 错误(?)输出
- apache-flink - 取消的 flink 作业没有释放 tm 和 jm 的使用内存
- r - R如何对行之间的部分重叠值进行分组?
- file - 如何使用 wget 下载特定的文件扩展名?
- sharepoint - 创建列表列会返回不需要的结果