是否可以使用* 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 word1': 'Word1'}, {'This is a word2': 'Word2'}]
答案 0 :(得分:1)
您可以使用列表推导通过迭代*args
来创建新的词典列表,就像这样
def Func(*args):
return [{'This is a word': arg} for arg in args]
print Func("word1")
# [{'This is a word': 'word1'}]
print Func("word1", "word2")
# [{'This is a word': 'word1'}, {'This is a word': 'word2'}]
答案 1 :(得分:1)
相当简单:
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'}]
答案 2 :(得分:1)
看起来你可能会选择有序的字典吗?
import collections
def Func2(*args):
return collections.OrderedDict(('This is a word' + str(i+1), arg) for i, arg in enumerate(args))
>>> Func2('a', 'b', 'c', 'd', 'e')
OrderedDict([('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')])
或者只是:
import collections
def Func2(*args):
return collections.OrderedDict((i+1, arg) for i, arg in enumerate(args))
>>> Func2('a', 'b', 'c', 'd', 'e')
OrderedDict([(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')])
这会让我更容易访问您的数据对象。
>>> foo = Func2('a', 'b', 'c', 'd', 'e')
>>> foo[1]
'a'
通过这种方式,我们看到我们已经实现了一种可由可修改索引访问的列表。