提问人:Maya_NG 提问时间:9/16/2022 最后编辑:mozwayMaya_NG 更新时间:9/16/2022 访问量:62
有没有办法将一串数字和单词更改为嵌套列表,其中名称与 Python 中的单个数字相关联?
Is there a way to change a string of numbers and words into a nested list, where the name are associated with their individual numbers in Python?
问:
示例字符串:
ex_name_age = "Hannah 12, Daniel 98, Maya 30, Elizabeth 96"
所需格式输出:
[['Hannah', 12],
['Daniel', 98],
['Maya', 30],
['Elizabeth', 96]]
我试过使用:
name_age_a = ex_name_age.split(", ")
name_age_a = [[val] for val in name_age_a]
print(name_age_a)
其结果是:
[['Hannah 12'],
['Daniel 98'],
['Maya 30'],
['Elizabeth 96']]
所以我大错特错了......
有谁知道如何解决这个问题,所以每个列表都会包含两者?[["string", integer],...]
答:
1赞
mozway
9/16/2022
#1
使用列表推导的一个选项:
[[name, int(age)]
for x in ex_name_age.split(', ')
for name, age in [x.split()]
]
输出:
[['Hannah', 12],
['Daniel', 98],
['Maya', 30],
['Elizabeth', 96]]
1赞
sametatila
9/16/2022
#2
实际上你做对了,但缺少第二次拆分。你可以试试这样。
name_age_a = ex_name_age.split(", ")
name_age_a = [[val.split(' ')] for val in name_age_a]
print(name_age_a)
评论
0赞
mozway
9/16/2022
不过,这不会执行到整数的转换;)
0赞
crunker99
9/16/2022
#3
每个 in 都是一个类似 的字符串。您需要在空白处拆分每个字符串。val
name_age_a
'Hannah 12'
' '
ex_name_age = "Hannah 12, Daniel 98, Maya 30, Elizabeth 96"
name_age_a = ex_name_age.split(", ")
print(name_age_a)
# ['Hannah 12', 'Daniel 98', 'Maya 30', 'Elizabeth 96']
out = []
for val in name_age_a:
name, age = val.split(' ') # unpack
out.append([name, int(age)])
print(out)
# [['Hannah', 12], ['Daniel', 98], ['Maya', 30], ['Elizabeth', 96]]
评论