我在列表中有多个字符串列表。我想将数字的字符串更改为整数。
例如: -
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]))
当我尝试上面的代码时,我收到了一个错误。
答案 0 :(得分:1)
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)
答案 1 :(得分:0)
这样的事情:
>>> 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']]