小编Tha*_*Cob的帖子

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

基本上,我有一个字符串给出如下:"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 …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension list

3
推荐指数
1
解决办法
502
查看次数

标签 统计

list ×1

list-comprehension ×1

python ×1