python-3.x 将字典的值转换为列表?[副本]

mwkjh3gx  于 2023-05-19  发布在  Python
关注(0)|答案(4)|浏览(114)

此问题已在此处有答案

How to convert a string of space- and comma- separated numbers into a list of int?(6个回答)
7年前关闭。
假设我收到了这个文本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]}
wh6knrhe

wh6knrhe1#

>>> 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
j91ykkif

j91ykkif2#

你已经完成了基本的步骤,剩下的步骤是:

  • 分割逗号split(',')上的值
  • 将字符串转换为整数int(i)

将这些步骤 Package 在一个for循环中,并对字典中的每个键/值对执行此操作。

for key, value in new_dictionary.items():
    new_dictionary[key] = [int(i) for i in value.split(',')]
bvk5enib

bvk5enib3#

下面是另一种使用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]}
czfnxgou

czfnxgou4#

你需要用“,”分割这个字典值,然后将它Map到int:

s['Female'] = map(int, s['Female'].split(','))

相关问题