gpt4 book ai didi

python - 列表理解——将一个列表中的字符串转换为另一个列表中的整数

转载 作者:太空宇宙 更新时间:2023-11-03 13:12:15 25 4
gpt4 key购买 nike

基本上,我给出的字符串如下:“56 65 74 100 99 68 86 180 90”。

我需要以这样一种方式转换它,以便我能够将构成上述数字的每个数字相加,即 56 将变为 5 + 6 将变为 11。

到目前为止,我采用了以下方法:

l = string.split()

new_l = []

# the below creates a list as follows: [['56'],['65'], ['74'] etc.]
for x in l:
new_l += [x.split()]

# while this list comprehension simply splits the list up: [['5','6'], etc.]
list_of_lists = [list(y) for x in new_l for y in x]

# now, if I could convert the numbers in those inner lists into integers,
# I'd be getting where I need to

# but for some reason, this list comprehension does not return what I need
l_o_l = [[int(x)] for x in y for y in list_of_lists]

最后一个列表推导式简单地返回了一些 9 和 0,而我终究无法弄清楚原因。

请原谅我对这个的无知,我已经阅读了一些解释,但它们似乎并不是我正在寻找的。

非常感谢所有帮助!

最佳答案

你可以大大简化这个:

>>> example = "56 65 74 100 99 68 86 180 90"
>>> example.split()
['56', '65', '74', '100', '99', '68', '86', '180', '90']

所以你真正需要的是:

>>> [sum(map(int,s)) for s in example.split()]
[11, 11, 11, 1, 18, 14, 14, 9, 9]
>>>

这里的关键是字符串已经是可迭代的。无需将它们转换为列表。

另外,请注意,您最后的推导式中的 for 表达式是倒过来的,应该会引发错误。相反,这可能是您的意思:

>>> [[int(x)] for y in list_of_lists for x in y]
[[5], [6], [6], [5], [7], [4], [1], [0], [0], [9], [9], [6], [8], [8], [6], [1], [8], [0], [9], [0]]

我不确定你是如何得到 9 和 0 的。

你可能想要的是这样的:

>>> l_o_l = [[int(y) for y in x] for x in list_of_lists]
>>> l_o_l
[[5, 6], [6, 5], [7, 4], [1, 0, 0], [9, 9], [6, 8], [8, 6], [1, 8, 0], [9, 0]]

然后,最后,使用以下内容:

>>> [sum(l) for l in l_o_l]
[11, 11, 11, 1, 18, 14, 14, 9, 9]
>>>

但同样,这种方法设计过度,因为字符串已经是可迭代的

关于python - 列表理解——将一个列表中的字符串转换为另一个列表中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40498088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com