如何迭代集合列表并将其转换为 Python3 中的字典
How to iterate over list of sets and converting it to a dictionary in Python3
我有以下格式的输入,我需要遍历它以将给定的集合转换成字典。
input = [{"Bob","87"}, {"Mike", "35"},{"Bob", "52"}, {"Jason","35"}, {"Mike", "55"}, {"Jessica", "99"}]
我的最终目标是让每个学生的平均分成为字典形式。
我试过了:
marks_dict ={}
for k,v in marks:
if k not in marks_dict.keys():
marks_dict[k] = v
else:
marks_dict[k].append(v)
print(marks_dict.keys())```
I am getting in output:
'87': 'Bob', '35': 'Mike', '52': 'Bob', 'Jason': '35', 'Mike': '55', '99': 'Jessica'}
sometimes :
Traceback (most recent call last):
File "/Users/rbhutada/Desktop/GSTest.gyp", line 7, in <module>
marks_dict[k].append(v)
AttributeError: 'str' object has no attribute 'append'
根据定义,集合是无序的。所以 {"Bob", "87"}
等同于 {"87", "Bob"}
.
所以你不想使用集合。按顺序使用元组(或列表):
input = [("Bob","87"), ("Mike", "35"),("Bob", "52"), ("Jason","35"), ("Mike", "55"), ("Jessica", "99")]
此外,当您初始化密钥时,使用列表 [v]
而不是标量 v
:
if k not in marks_dict.keys():
marks_dict[k] = [v]
否则以后无法追加。
因此代码变为(input
更改为 marks
因此它适合代码):
marks = [("Bob","87"), ("Mike", "35"),("Bob", "52"), ("Jason","35"), ("Mike", "55"), ("Jessica", "99")]
marks_dict ={}
for k,v in marks:
if k not in marks_dict.keys():
marks_dict[k] = [v]
else:
marks_dict[k].append(v)
print(marks_dict.keys())
print(marks_dict)
使用此输出:
dict_keys(['Bob', 'Mike', 'Jason', 'Jessica'])
{'Bob': ['87', '52'], 'Mike': ['35', '55'], 'Jason': ['35'], 'Jessica': ['99']}
从那里我将留给你计算平均值。
不过,我确实建议从一开始就使用整数作为标记,而不是字符串,如果它们都是整数的话。例如,87
而不是 "87"
。
如果你真的碰巧在列表中有集合,你需要先把它转换成更容易处理的数据类型。之后,您可以使用 itertools.groupby
:
from itertools import groupby
lst = [{"Bob", "87"}, {"Mike", "35"}, {"Bob", "52"}, {"Jason", "35"}, {"Mike", "55"}, {"Jessica", "99"}]
def convert(item):
""" Convert it to a tuple instead. """
x, y = item
if x.isdigit():
return y, x
else:
return x, y
lst = sorted(map(convert, lst), key=lambda item: item[0])
result = {}
for name, values in groupby(lst, key=lambda item: item[0]):
marks = [int(x[1]) for x in values]
result[name] = sum(marks) / len(marks)
print(result)
结果是
{'Bob': 69.5, 'Jason': 35.0, 'Jessica': 99.0, 'Mike': 45.0}
但是首先不要使用集合,也不要使用像 input
、dict
或 list
.
这样的变量名
我有以下格式的输入,我需要遍历它以将给定的集合转换成字典。
input = [{"Bob","87"}, {"Mike", "35"},{"Bob", "52"}, {"Jason","35"}, {"Mike", "55"}, {"Jessica", "99"}]
我的最终目标是让每个学生的平均分成为字典形式。
我试过了:
marks_dict ={}
for k,v in marks:
if k not in marks_dict.keys():
marks_dict[k] = v
else:
marks_dict[k].append(v)
print(marks_dict.keys())```
I am getting in output:
'87': 'Bob', '35': 'Mike', '52': 'Bob', 'Jason': '35', 'Mike': '55', '99': 'Jessica'}
sometimes :
Traceback (most recent call last):
File "/Users/rbhutada/Desktop/GSTest.gyp", line 7, in <module>
marks_dict[k].append(v)
AttributeError: 'str' object has no attribute 'append'
根据定义,集合是无序的。所以 {"Bob", "87"}
等同于 {"87", "Bob"}
.
所以你不想使用集合。按顺序使用元组(或列表):
input = [("Bob","87"), ("Mike", "35"),("Bob", "52"), ("Jason","35"), ("Mike", "55"), ("Jessica", "99")]
此外,当您初始化密钥时,使用列表 [v]
而不是标量 v
:
if k not in marks_dict.keys():
marks_dict[k] = [v]
否则以后无法追加。
因此代码变为(input
更改为 marks
因此它适合代码):
marks = [("Bob","87"), ("Mike", "35"),("Bob", "52"), ("Jason","35"), ("Mike", "55"), ("Jessica", "99")]
marks_dict ={}
for k,v in marks:
if k not in marks_dict.keys():
marks_dict[k] = [v]
else:
marks_dict[k].append(v)
print(marks_dict.keys())
print(marks_dict)
使用此输出:
dict_keys(['Bob', 'Mike', 'Jason', 'Jessica'])
{'Bob': ['87', '52'], 'Mike': ['35', '55'], 'Jason': ['35'], 'Jessica': ['99']}
从那里我将留给你计算平均值。
不过,我确实建议从一开始就使用整数作为标记,而不是字符串,如果它们都是整数的话。例如,87
而不是 "87"
。
如果你真的碰巧在列表中有集合,你需要先把它转换成更容易处理的数据类型。之后,您可以使用 itertools.groupby
:
from itertools import groupby
lst = [{"Bob", "87"}, {"Mike", "35"}, {"Bob", "52"}, {"Jason", "35"}, {"Mike", "55"}, {"Jessica", "99"}]
def convert(item):
""" Convert it to a tuple instead. """
x, y = item
if x.isdigit():
return y, x
else:
return x, y
lst = sorted(map(convert, lst), key=lambda item: item[0])
result = {}
for name, values in groupby(lst, key=lambda item: item[0]):
marks = [int(x[1]) for x in values]
result[name] = sum(marks) / len(marks)
print(result)
结果是
{'Bob': 69.5, 'Jason': 35.0, 'Jessica': 99.0, 'Mike': 45.0}
但是首先不要使用集合,也不要使用像 input
、dict
或 list
.