[英]How to split the list of values in a sublist based on the first number in a element?
I have a list which looks like:我有一个看起来像的列表:
lines =
['1 22698U 93041A 08176.51164820 .00000248 00000-',
'2 22698 089.5192 046.4765 0091800 046.2114 314.6604',
'1 22698U 93041A 08176.93361871 +.00000248 +00000121',
'2 22698 089.5191 046.4531 0091744 044.8831 315.9716',
'1 22698U 93041A 08177.84788861 .00000094 00000-',
'2 22698 089.5188 046.4030 0091715 041.9519 318.8655']
I would like to split lines
into 3 sublists like:我想将
lines
拆分为 3 个子列表,例如:
sublist_1 =
['1 22698U 93041A 08176.51164820 .00000248 00000-',
'2 22698 089.5192 046.4765 0091800 046.2114 314.6604']
sublist_2 =
['1 22698U 93041A 08176.93361871 +.00000248 +00000121',
'2 22698 089.5191 046.4531 0091744 044.8831 315.9716',]
sublist_3 =
['1 22698U 93041A 08177.84788861 .00000094 00000-',
'2 22698 089.5188 046.4030 0091715 041.9519 318.8655']
The splitting should be based on the first number of a value in a list.拆分应基于列表中值的第一个数字。 Like sublist should contain one value from a sequence that starts with '1' and another that starts with '2'
Like sublist 应该包含一个以“1”开头的序列和另一个以“2”开头的值
I will appreciate any suggestions on how can I manage it.我将不胜感激有关如何管理它的任何建议。
Use numpy.reshape()使用 numpy.reshape()
import numpy as np
lines = np.array(lines)
lines = lines.reshape(-1, 2)
lines[0], lines[1] and lines[2] are your sublists respectively. lines[0]、lines[1] 和 lines[2] 分别是您的子列表。
sublist_1, sublist_2, sublist_3 = lines
You can do it by list comprehension, enumerate and list slicing like你可以通过列表理解、枚举和列表切片来做到这一点
lines =['1 22698U 93041A 08176.51164820 .00000248 00000-',
'2 22698 089.5192 046.4765 0091800 046.2114 314.6604',
'1 22698U 93041A 08176.93361871 +.00000248 +00000121',
'2 22698 089.5191 046.4531 0091744 044.8831 315.9716',
'1 22698U 93041A 08177.84788861 .00000094 00000-',
'2 22698 089.5188 046.4030 0091715 041.9519 318.8655']
sublist_1, sublist_2, sublist_3 = [[v, lines[i*2+1]] for i, v in enumerate(lines[::2])]
OR with zip或与 zip
sublist_1, sublist_2, sublist_3 = (list(v) for v in zip(lines[::2], lines[1::2]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.