作为输入,我有一个字典列表,如下例所示
list = [
{"name": "John", "age": 36, "gender": "Male"},
{"name": "Lisa", "age": 40, "gender": "Female"},
{"name": "Mary", "age": 26, "gender": "Female"},
...
]
我想运行一个函数,使用字典中的值作为参数,并使用列表中的每个字典
def value(person_name, person_age, person_gender):
"returns a value based on arguments"
作为输出,我需要返回该函数为每个字典计算的值的列表。例如:
[def value(John, 36, Male), def value(Lisa, 40, Female), def value(Mary, 26, Female), ...]
感谢您的帮助:)
答案 0 :(得分:2)
您可以使用列表推导。
result = [values(p['name'], p['age'], p['gender']) for p in list]
答案 1 :(得分:1)
kwargs在这里应该很有用,请注意,尽管函数参数的名称需要与字典的键完全匹配才能使用
list = [
{"name": "John", "age": 36, "gender": "Male"},
{"name": "Lisa", "age": 40, "gender": "Female"},
{"name": "Mary", "age": 26, "gender": "Female"},
]
def func1(name, age, gender):
print("1: ", name)
def func2(name, age, gender):
print("2: ", name)
def func3(name, age, gender):
print("3: ", name)
for d in list:
func1(**d)
func2(**d)
func3(**d)
答案 2 :(得分:0)
如果将函数参数的名称与dict
的键相同,则可以简单地用**
对其进行解压缩,如下例所示:
data = [
{"name": "John", "age": 36, "gender": "Male"},
{"name": "Lisa", "age": 40, "gender": "Female"},
{"name": "Mary", "age": 26, "gender": "Female"}
]
def value(name, age, gender):
return 'Name: {}, Age: {}, Gender: {}.'.format(name, age, gender)
[value(**i) for i in data]
#['Name: John, Age: 36, Gender: Male.',
# 'Name: Lisa, Age: 40, Gender: Female.',
# 'Name: Mary, Age: 26, Gender: Female.']
答案 3 :(得分:0)
您可以发送整个词典并将其解压缩到功能中
def value(x):
name = x['name']
age = x['age']
gender = x['gender']
# do something
# return something
for i in lista: # full loop
value(i)
[value(i) for i in lista] # list comprehension
答案 4 :(得分:0)
map
的简单情况:
data = [
{"name": "John", "age": 36, "gender": "Male"},
{"name": "Lisa", "age": 40, "gender": "Female"},
{"name": "Mary", "age": 26, "gender": "Female"},
...
]
def value(**kwargs):
...
result = list(map(data, value))