[英]Perform operation on floats in list value that contains both floats and strings
I have a dictionary in Python 3 in which all key-value pairs have the following structure:我在 Python 3 中有一个字典,其中所有键值对都具有以下结构:
my_dict = {'Jerry': [0.4, 'Queens', 0.6, 'Knicks']}
This means that the value is always a list with float, string, float, string.这意味着该值始终是一个包含浮点数、字符串、浮点数、字符串的列表。
I need to modify the values so that the two floats are averaged, and that the new dictionary looks as follows:我需要修改这些值,以便平均两个浮点数,并且新字典如下所示:
new_dict = {'Jerry': [0.5, 'Queens', 'Knicks]}
I have tried a for
loop that selects the floats from the value list based on their indexes, but Python doesn't let me index through it.我尝试了一个
for
循环,它根据索引从值列表中选择浮点数,但是 Python 不允许我通过它索引。
for k, v in my_dict.items():
average = sum(v[0], v[1])/2
my_dict[k] = [average, v[1], v[3]]
This returns这返回
TypeError: 'float' object is not iterable
How could I select the floats to work out the average?我怎么能 select 浮点数来计算平均值?
You need to pass an iterable
to the sum()
function, so make the values v[0]
and v[1]
to a list by adding a [
and ]
您需要将一个
iterable
对象传递给sum()
function,因此通过添加[
和]
将值v[0]
和v[1]
设置为列表
my_dict = {'Jerry': [0.4, 'Queens', 0.6, 'Knicks']}
for k, v in my_dict.items():
average = sum([v[0], v[2]])/2
my_dict[k] = [average, v[1], v[3]]
print(my_dict)
Output: Output:
{'Jerry': [0.5, 'Queens', 'Knicks']}
my_dict = {'Jerry': [0.4, 'Queens', 0.6, 'Knicks'], 'Berry': [0.5, 'Queens', 0.1, 'Knicks']}
my_dict = {k:[(v[0]+v[2])/2, v[1], v[3]] for k,v in my_dict.items()}
print(my_dict)
Output: Output:
{'Jerry': [0.5, 'Queens', 'Knicks'], 'Berry': [0.3, 'Queens', 'Knicks']}
Iterate through the key
, value
pairs, and create a temporary list to store numeric and string data, and iterate each value list and append to numbers
/ strings
lists based on type
, finally find the average
and add it to the resulting dictionary.遍历
key
、 value
对,并创建一个临时列表来存储数字和字符串数据,并根据type
将每个 value 列表和 append 迭代到numbers
/ strings
列表中,最后找到average
并将其添加到结果字典中。
my_dict = {'Jerry': [0.4, 'Queens', 0.6, 'Knicks']}
result = {}
for key,value in my_dict.items():
numbers = []
strings =[]
for item in value:
if type(item) is float:
numbers.append(item)
else:
strings.append(item)
result[key] = [sum(numbers)/len(numbers)] + strings
OUTPUT : OUTPUT :
{'Jerry': [0.5, 'Queens', 'Knicks']}
PS : This solution will work even if you have more or less number of items in the value list of the given dictionary. PS :即使您在给定字典的值列表中有更多或更少的项目,此解决方案也将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.