简体   繁体   English

Python:如何将特定数量的字符上的字符串切成列表?

[英]Python: How to slice a string on a specific number of characters into a list?

I am reading a line of text data and I want to split the line into a list of values. 我正在阅读一行文本数据,我想将该行拆分为值列表。 For example the line has four numbers, each one allotted 5 spaces, so if the numbers are 18, 295, -9999, and 1780 then the original line will look like this (with ^ characters denoting the start and end of line, not included in actual input data): 例如,该行有四个数字,每个数字分配5个空格,因此如果数字是18,295,-9999和1780,则原始行将如下所示(^字符表示行的开头和结尾,不包括在内在实际输入数据中):

^   18  295-9999 1780^

I want to split the line into a list of its actual component values: 我想将该行拆分为其实际组件值的列表:

[18, 295, -9999, 1780]

I know the number of values that the list should contain (in the example above it's 4), and I know exactly how many spaces each value takes up in the string (in the example above it's 5). 我知道列表应该包含的值的数量(在上面的示例中为4),并且我确切地知道每个值在字符串中占用多少空格(在上面的示例中为5)。 I can create a loop to do this splitting, like this: 我可以创建一个循环来执行此拆分,如下所示:

values = []
for i in range(4):
    values.append(line[i*5:5])

Is there a more efficient or more "Pythonic" way of doing this? 有更高效或更“Pythonic”的方式吗?

Thanks in advance for your help. 在此先感谢您的帮助。

Using slicing... 使用切片......

>>> [int(s[i:i+5]) for i in xrange(0, len(s), 5)]
[18, 295, -9999, 1780]

Or - if you really wanted to, some people find re a bit more readable... (just throwing this in as an alternative for reference - don't shoot me!) 或者-如果你真的想,有些人觉得re有点更具可读性...(只是扔在此作为参考的选择-不要拍我!)

>>> map(int, re.findall('.{5}', s))
[18, 295, -9999, 1780]

Here is another possible solution: 这是另一种可能的解决方案

x = '   18  295-9999 1780'

def split_up(x):
    return map(int, x.replace('-', ' -').split())

Result 结果

>>> split_up(x)
[18, 295, -9999, 1780]

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

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