简体   繁体   English

如何在 Python 中转换`str.split()` 的元素?

[英]How to convert elements of `str.split()` in Python?

I have the following:我有以下几点:

[line.split(' ') for line in [
        line.rstrip() for line in file.readlines()]]

which returns a list of list of strings.它返回一个字符串列表列表。 I know I could do the following to convert it to a list of list of integers:我知道我可以执行以下操作将其转换为整数列表:

    for row in tree:
        row[:] = map(int, row[:])

Can that be done inline as the lines are being processed?可以在处理行时内联完成吗?

Some sample data:一些示例数据:

59
73 41
52 40 09
26 53 06 34
10 51 87 86 81

You could use你可以用

data = """
59
73 41
52 40 09
26 53 06 34
10 51 87 86 81
"""

result = [[int(x) for x in line.split()] for line in data.split("\n") if line]
print(result)

Which yields哪个产量

[[59], [73, 41], [52, 40, 9], [26, 53, 6, 34], [10, 51, 87, 86, 81]]

Note that this only works if you only have integers.请注意,这仅在您只有整数时才有效。
To have some error management, you could use:要进行一些错误管理,您可以使用:

data = """
59 some junk here
73 41
52 40 09
26 53 06 34
10 51 87 86 81
"""

def makeint(line):
    for x in line.split():
        try:
            yield int(x)
        except ValueError:
            pass

result = [[x for x in makeint(line)] for line in data.split("\n") if line]
print(result)

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

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