这是“我的Python”代码中的列表。我想在无
之前和之后通过中断来分隔列表lists = [
'a',
'b',
'c',
'None',
'd',
'e',
'e',
'f',
'None',
'g',
'h',
'i',
'i',
'i',
'None',
'aa',
'aa',
'aa',
'aa',
'aa',
'ab',
'ac',
]
因此,预期结果将是:
out = ['a','b','c',], ['d','e','e','f',], ['g','h','i','i','i',], ['aa','aa','aa','aa','aa','ab','ac']
答案 0 :(得分:5)
from itertools import groupby
items = [
"A",
"B",
"C",
"None",
"D",
"E",
"None",
"F",
"G",
"H"
]
lists = [list(group) for key, group in groupby(items, key=lambda x: x != "None") if key]
print(lists)
输出:
[['A', 'B', 'C'], ['D', 'E'], ['F', 'G', 'H']]
答案 1 :(得分:1)
lists = [<your data>]
out = []
temp = []
for item in lists:
if item != 'None':
temp.append(item)
else:
out.append(temp)
temp = []
# Catch that list temp list
if temp:
out.append(temp)
del temp
print(out)
输出:[['a','b','c'],['d','e','e','f'],['g', 'h','i','i','i'],['aa','aa','aa','aa','aa','ab','ac']]
答案 2 :(得分:0)
我已使用您提供的列表来测试我的代码。
代码:
result_list = []
temp_list = []
for elem in lists:
if elem == "None":
result_list.append(temp_list)
temp_list = []
continue
temp_list.append(elem)
result_list.append(temp_list) if temp_list else None
print(result_list)
输出:
>>> python test.py
[['a', 'b', 'c'], ['d', 'e', 'e', 'f'], ['g', 'h', 'i', 'i', 'i'], ['aa', 'aa', 'aa', 'aa', 'aa', 'ab', 'ac']]