在 Python 的元素中出现斜杠之前拆分列表
Split a list before a slash appears in an element for Python
我有一个列表
list = ['09/30', '16:30','A','B','5','100','10/01','16:30','C','D','4',
'10/02','16:30','E','F']
我希望它每次在带有 /.
的元素之前拆分成一个新列表
希望有这样的东西:
list = ['09/30', '16:30','A','B','5','100'], ['10/01','16:30','C','D','4'], ['10/02','16:30','E','F']
然后我想用 NA 填写较短的列表
list = [['09/30', '16:30','A','B','5','100'], ['10/01','16:30','C','D','4', 'NA'], ['10/02','16:30','E','F', 'NA', 'NA]]
我确定这很简单,我只是想念它。
您可以轻松地使用 itertools.groupby 将连续的元素分组到同一个“斜杠”元素下。然后得到一个组的最大长度,并将“NA”附加到其他小于该长度的组。
from itertools import groupby, zip_longest
class SlashGrouper:
def __init__(self):
self.group_id = 0
def __call__(self, text):
if "/" in text:
self.group_id += 1
return self.group_id
my_list = ['09/30', '16:30','A','B','5','100','10/01','16:30','C','D','4', '10/02','16:30','E','F']
my_list_grouped = [list(group) for _, group in groupby(my_list, key=SlashGrouper())]
print(my_list_grouped)
max_len = len(max(my_list_grouped, key=lambda val: len(val)))
for group in my_list_grouped:
group.extend(["NA"] * (max_len - len(group)))
print(my_list_grouped)
输出
[['09/30', '16:30', 'A', 'B', '5', '100'], ['10/01', '16:30', 'C', 'D', '4'], ['10/02', '16:30', 'E', 'F']]
[['09/30', '16:30', 'A', 'B', '5', '100'], ['10/01', '16:30', 'C', 'D', '4', 'NA'], ['10/02', '16:30', 'E', 'F', 'NA', 'NA']]
我有一个列表
list = ['09/30', '16:30','A','B','5','100','10/01','16:30','C','D','4',
'10/02','16:30','E','F']
我希望它每次在带有 /.
的元素之前拆分成一个新列表希望有这样的东西:
list = ['09/30', '16:30','A','B','5','100'], ['10/01','16:30','C','D','4'], ['10/02','16:30','E','F']
然后我想用 NA 填写较短的列表
list = [['09/30', '16:30','A','B','5','100'], ['10/01','16:30','C','D','4', 'NA'], ['10/02','16:30','E','F', 'NA', 'NA]]
我确定这很简单,我只是想念它。
您可以轻松地使用 itertools.groupby 将连续的元素分组到同一个“斜杠”元素下。然后得到一个组的最大长度,并将“NA”附加到其他小于该长度的组。
from itertools import groupby, zip_longest
class SlashGrouper:
def __init__(self):
self.group_id = 0
def __call__(self, text):
if "/" in text:
self.group_id += 1
return self.group_id
my_list = ['09/30', '16:30','A','B','5','100','10/01','16:30','C','D','4', '10/02','16:30','E','F']
my_list_grouped = [list(group) for _, group in groupby(my_list, key=SlashGrouper())]
print(my_list_grouped)
max_len = len(max(my_list_grouped, key=lambda val: len(val)))
for group in my_list_grouped:
group.extend(["NA"] * (max_len - len(group)))
print(my_list_grouped)
输出
[['09/30', '16:30', 'A', 'B', '5', '100'], ['10/01', '16:30', 'C', 'D', '4'], ['10/02', '16:30', 'E', 'F']]
[['09/30', '16:30', 'A', 'B', '5', '100'], ['10/01', '16:30', 'C', 'D', '4', 'NA'], ['10/02', '16:30', 'E', 'F', 'NA', 'NA']]