加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:55:45 所属栏目:Python 来源:网络整理
导读:基本上,我有一个字符串给出如下:“56 65 74 100 99 68 86 180 90”. 我需要以这样一种方式转换它,以便我能够将构成上述数字的每个单独数字相加,即56将变为5 6将变为11. 到目前为止,我采取了以下方法: l = string.split()new_l = []# the below creates a l
基本上,我有一个字符串给出如下:“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,1,18,14,9,9]
>>>

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

另请注意,您的最后一次理解具有向后的for-expressions并且应该抛出错误.相反,这可能是你的意思:

>>> [[int(x)] for y in list_of_lists for x in y]
[[5],[6],[5],[7],[4],[1],[0],[9],[8],[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],[9,9],8],[8,8,0]]

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读