python - 如何在函数中使用 *args 返回字典列表?

标签 python function dictionary arguments args

是否可以使用 *args 生成字典列表,其中每个字典都具有完全相同的键并且每个值都是 arg?

比如我目前有这个功能:

def Func(word1,word2):
    return [{'This is a word':word1},{'This is a word':word2}]

我是这样使用它的:

print Func("Word1","Word2")

返回:

[{'This is a word': 'Word1'}, {'This is a word': 'Word2'}] 

问题是我想用 1 个词或 5 个词来使用这个函数。我怎么能改用 *args 呢?是否可以启动这样的功能:

def Func(*args):

如果我能在“This is a word”有这样的计数的情况下生成以下内容,那就太棒了:

[{'This is a word1': 'Word1'}, {'This is a word2': 'Word2'}] 

最佳答案

做起来相当简单:

def Func(*args):
    return [{'This is a word': arg} for arg in args]


>>> Func('foo', 'bar', 'baz')
[{'This is a word': 'foo'}, {'This is a word': 'bar'}, {'This is a word': 'baz'}]

>>> Func('a', 'b', 'c', 'd', 'e')
[{'This is a word': 'a'}, {'This is a word': 'b'}, {'This is a word': 'c'}, {'This is a word': 'd'}, {'This is a word': 'e'}]

为了满足您的额外要求:

def Func(*args):
    return [{'This is a word' + str(i+1): arg} for i, arg in enumerate(args)]


>>> Func('a', 'b', 'c', 'd', 'e')
[{'This is a word1': 'a'}, {'This is a word2': 'b'}, {'This is a word3': 'c'}, {'This is a word4': 'd'}, {'This is a word5': 'e'}]

关于python - 如何在函数中使用 *args 返回字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21347081/

相关文章:

python - 检查矩阵键是否按运行顺序 - python

python,清理列表

c# - 增加字典中的数值

python - 将 csv 列连接到字符串并打印特定值

python - 从 azure blob 存储中读取多行

javascript - 如何仅将 jquery 应用于使用 if 语句选择的元素?

r - R : cannot open file 'specdata/001.csv' : No such file or directory [duplicate]

list - 使用 Haskell 中的分隔字符将字符串分成更多部分

java - 通用编程 : error when trying to put values in an EnumMap

c++ - 为什么我不能在 map 中放置一个迭代器?