简体   繁体   English

将字符串列表转换为 int [暂停]

[英]Convert a list of strings into int [on hold]

I have:我有:

[['2,4,2'],['1,2,2,2,1'],['0,2,4,2'],['0,1,6,1'],['0,1,6,1'],['0,2,4,2'],['1,2,2,2,1'],['2,4,2']]

and I would like to have:我想拥有:

[[2,4,2],[1,2,2,2,1],[0,2,4,2],[0,1,6,1],[0,1,6,1],[0,2,4,2],[1,2,2,2,1],[2,4,2]]

How could I make it?我怎么能做到?

Try a list comprehension:尝试列表理解:

>>> [[int(x) for x in y[0].split(',')] for y in l]
[[2, 4, 2], [1, 2, 2, 2, 1], [0, 2, 4, 2], [0, 1, 6, 1], [0, 1, 6, 1], [0, 2, 4, 2], [1, 2, 2, 2, 1], [2, 4, 2]]

You can try this:你可以试试这个:

l = [['2,4,2'],['1,2,2,2,1'],['0,2,4,2'],['0,1,6,1'],['0,1,6,1'],['0,2,4,2'], 
['1,2,2,2,1'],['2,4,2']]
ans = []
for i in l:
    temp = []
    tokens = (i[0].split(','))
    for j in tokens:
        temp.append(int(j))
    ans.append(temp)
print(ans)

Iterate take the first element split by , you will get a list then convert each element to integer and comprehend the list like this迭代将第一个元素拆分为,您将得到一个列表,然后将每个元素转换为 integer 并像这样理解列表

list_input = [['2,4,2'],['1,2,2,2,1'],['0,2,4,2'],['0,1,6,1'],['0,1,6,1'],['0,2,4,2'],['1,2,2,2,1'],['2,4,2']]
[map(lambda x: int(x),val[0].split(",")) for val in list_input]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM