问题
The input:
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']
The desired output:
['22774080.570 7','none','1762178.392 7','1346501.808 8','22774088.434 8'],
['20194290.688 8','none','-2867460.044 8', .... ]
回答1:
I've made a few assumptions here, and this is probably not the most elegant solution, but given that your matching None based on the length of space, this will work
[[(None if a.strip() == 'None' else a.strip())
for a in l.replace(' ', ' None ').split(' ') if a != ''
] for l in lst]
this is currently implemented as a list comprehension, but could easily be spread over multiple lines for readability as such
new_list = []
for l in lst:
sub_list = []
for a in l.replace(' ', ' None ').split(' '):
if a != '':
item = a.strip()
sub_list.append(None if item == 'None' else item)
new_list.append(sub_list)
either method yields the same 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'
]
]
Bear in mind that any changes to the width of spaces used to define 'None' will impact the function of this implementation.
回答2:
I will not answer your question right away because it is not how stackoverflow works but I will give you some hints.
HINTS
First, you can iterate over each line of your first list
lst
using a for loop.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.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
)
END
I will edit my answer with a working function as soon as you edit yours with a proper try. Good luck!
EDIT
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)
Will output:
['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']
来源:https://stackoverflow.com/questions/40507313/transform-a-list