lis中的字符串列表

2024-04-25 23:00:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多个字符串列表,在一个列表中。我想把数字字符串改成整数。你知道吗

例如:

L1=[['123','string','list']['words','python','456']['code','678','links']]

我想要的是:

[[123,'string','list']['words','python',456]['code',678,'links']]

我试过用-

W=range(len(L1))       
Q=range(2)
if (L1[W][Q]).isdigit():
   (L1[W][Q])=(int(L1[W][Q]))

当我尝试上面的代码时,我得到了一个错误。你知道吗


Tags: 字符串l1列表stringlenifcoderange
2条回答

像这样:

>>> mylist = [['123','string','list'], ['words','python','456'], ['code','678','links']]
>>> [ [(int(item) if item.isdigit() else item) for item in sublist] for sublist in mylist]
[[123, 'string', 'list'], ['words', 'python', 456], ['code', 678, 'links']]

使用str.isdigit()

L1=[['123','string','list'],['words','python','456'],['code','678','links']]
for item in L1:
    for i in range(0,len(item)):
        if(item[i].isdigit()):
            item[i] = int(item[i])

print(L1)

相关问题 更多 >