假设我收到了此文age_gender.txt
Female:18,36,35,49,19
Male:23,22,26,26,26
这是我到目前为止的代码
file = open("age_gender.txt")
contents = file.read().splitlines()
new_dictionary = dict(item.split(":") for item in contents)
return new_dictionary
当我调用函数readfile()
时,这是我得到的输出,但值列表仍然是引号。如何将每个值转换为列表?
{'Female': '18,36,35,49,19', 'Male': '23,22,26,26,26'}
我想要实现的输出是这样的
{'Female': [18,36,35,49,19], 'Male': [23,22,26,26,26]}
答案 0 :(得分:2)
>>> a
'Female:18,36,35,49,19,19,40,23,22,22,23,18,36,35,49,19,19,18,36,18,36,35,12,19,19,18,23,22,22,23'
>>> a.split(':')
['Female', '18,36,35,49,19,19,40,23,22,22,23,18,36,35,49,19,19,18,36,18,36,35,12,19,19,18,23,22,22,23']
>>> a.split(':')[1].split(',')
['18', '36', '35', '49', '19', '19', '40', '23', '22', '22', '23', '18', '36', '35', '49', '19', '19', '18', '36', '18', '36', '35', '12', '19', '19', '18', '23', '22', '22', '23']
>>> new_dictionary = dict({a.split(':')[0]:map(int,a.split(':')[1].split(','))})
>>> new_dictionary
{'Female': [18, 36, 35, 49, 19, 19, 40, 23, 22, 22, 23, 18, 36, 35, 49, 19, 19, 18, 36, 18, 36, 35, 12, 19, 19, 18, 23, 22, 22, 23]}
将其应用于您的代码:
file = open("age_gender.txt")
contents = file.read().splitlines()
new_dictionary = dict()
for item in contents:
tmp = item.split(':')
new_dictionary[tmp[0]] = list(map(int, tmp[1].split(',')))
return new_dictionary
答案 1 :(得分:2)
你已经完成了基础知识,剩下的步骤是:
split(',')
int(i)
在for
循环中包装这些步骤,并为字典的每个键/值对执行此操作。
for key, value in new_dictionary.items():
new_dictionary[key] = [int(i) for i in value.split(',')]
答案 2 :(得分:2)
这是使用ast.literal_eval
将年龄转换为Python列表的另一种方法。它具有支持所有基本数据类型的优点,例如, float,没有显式转换:
from ast import literal_eval
with open('age_gender.txt') as f:
d = {gender: literal_eval(ages) for gender, ages in (line.split(':') for line in f)}
这将生成一个以元组为值的字典:
{'Male': (23, 22, 26, 26, 26), 'Female': (18, 36, 35, 49, 19)}
如果你确实需要列表,你可以转换元组:
with open('age_gender.txt') as f:
d = {gender: list(literal_eval(ages)) for gender, ages in (line.split(':') for line in f)}
{'Male': [23, 22, 26, 26, 26], 'Female': [18, 36, 35, 49, 19]}
答案 3 :(得分:1)
您需要将此字典值拆分为","然后将其映射到int:
s['Female'] = map(int, s['Female'].split(','))