转换列表 [英] Transform a list

查看:320
本文介绍了转换列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入:

 lst=[ '  22774080.570 7                   1762178.392 7   1346501.808 8  22774088.434 8\n',
     '  20194290.688 8                  -2867460.044 8  -2213132.457 9  20194298.629 9\n']

所需的输出:

['22774080.570 7','none','1762178.392 7','1346501.808 8','22774088.434 8'],
['20194290.688 8','none','-2867460.044 8', .... ]


推荐答案

我不会马上回答你的问题,因为它不是stackoverflow的工作方式,但我会给你一些提示。

I will not answer your question right away because it is not how stackoverflow works but I will give you some hints.

HINTS


  • 首先,您可以迭代第一个列表的每一行 lst 使用 for 循环

然后,你需要分割这一行的每个数字,幸运的是,它总是需要16个字符。
在python中,有几种方法可以做到这一点。对您的良好培训将是使用 范围功能中为循环。然后在python字符串中使用切片

Then, you need to split every numbers of this line, luckily for you, it took always 16 characters. In python, there is severals way to do so. A good training for you will be to use the range function in a for loop. Then use slicing in python strings.

现在,它可能在每个数字的开头都有一些额外的空格。删除它们的好方法是使用 strip()功能

Now, it could remains some extra spaces in the beginning of every numbers. A good way to remove them is to use the strip() function.

您需要做的最后一件事是 将每个清理字符串添加到新列表中 (例如结果

Last thing you need to do is to append every clean strings to a new list (e.g. result)

结束

只要您正确地尝试编辑您的答案,我将使用工作函数编辑我的答案。祝你好运!

I will edit my answer with a working function as soon as you edit yours with a proper try. Good luck!

编辑

因为我的同名@Max切斯特菲尔德已经给了回答,我会给我的。您可以使用生成器来匹配,而不是使用列表列表完全所需的输出

Since my namesake @Max Chesterfield already gave an answer, I'll give mine. Instead of using lists of list, you can use a generator to match exactly the desired output

def extract_line():
    for line in lst:
        result = []
        for i in range(0, len(line) - 1, 16):
            numbers = line[i:i + 16].strip()
            result.append(numbers if numbers else None)
        yield result

for result in extract_line():
    print(result)

将输出:

['22774080.570 7', None, '1762178.392 7', '1346501.808 8', '22774088.434 8']
['20194290.688 8', None, '-2867460.044 8', '-2213132.457 9', '20194298.629 9']

这篇关于转换列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆