python – List comprehension – 将一个列表中的字符串转换为另一个列表中的整数

基本上,我有一个字符串给出如下:“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-expressions并且应该抛出错误.相反,这可能是你的意思:

>>> [[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]
>>> 

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

点赞