如何仅将字符串列表的一部分转换为整数

AR.*_*ard 5 python int list python-3.x

我有一个列表列表,例如:

[['c', '2', '3', '4', 'd', '1'], ['e', '14', '16', '18', 'f', '1'], etc.]
Run Code Online (Sandbox Code Playgroud)

它们都遵循相同的模式(一个字符串,三个数字字符串,一个字符串,一个数字字符串)。我想将所有数字字符串都转换为整数,但这样做有困难。

I have tried an exception loop, which doesn't seem to be working (I'm not sure why). I know its targeting the sublists as originally I got a value error of int() doesn't recognise base 10 'c' (the first letter in the first element of the sublist.

[['c', '2', '3', '4', 'd', '1'], ['e', '14', '16', '18', 'f', '1'], etc.]
Run Code Online (Sandbox Code Playgroud)

When I print the results with the exception loop in it, it still produces a list of lists as if the exception wasn't there in the first place. e.g.

[['c', '2', '3', '4', 'd', '1'], ['e', '14', '16', '18', 'f', '1'], etc.] 
Run Code Online (Sandbox Code Playgroud)

whereas I expect it to be:

[['c', 2, 3, 4, 'd', 1], ['e', 14, 16, 18, 'f', 1], etc.]
Run Code Online (Sandbox Code Playgroud)

这是一个数据集分析,因此需要保留在列表格式列表中(因此,我不能仅使用rows.append来定位列表,因为它改变了分割最终数据的方式)。我在想,如果我无法解决这个问题,我可能会尝试将完整列表转换为元组,并使用字符异常循环,然后尝试将其转换并拆分回列表列表。我们将不胜感激,或者以其他方式获得此结果的任何帮助或理解,为什么该循环不起作用。

谢谢!

U10*_*ard 3

使用:

print([[int(x) if x.isdigit() else x for x in i] for i in rows])
Run Code Online (Sandbox Code Playgroud)

完整代码:

rows = []
with open(path) as infile:
    for line in infile:
        line = line.strip()
        if not line:
            continue
        rows.append(line.split("\t"))
rows = [[int(x) if x.isdigit() else x for x in i] for i in rows]
del rows[0]
Run Code Online (Sandbox Code Playgroud)