Python 如何根据条件拆分元组列表?
我有一个元组列表:Python 如何根据条件拆分元组列表?,python,list,split,tuples,Python,List,Split,Tuples,我有一个元组列表: my_list = [(1,'a','b','c'), (2,'d','e','f'), (3,'g','h','i'), (1,'j','k','l'), (2,'m','n','o'), (1,'p','q','r'), (2,'s','t','u')] 我需要在元组的子列表上拆分它,从第一项为“1”的元组开始 [(1,'a','b','c'), (2,'d','e','f'), (3,'g','h','i')] [(1,'j','k','l'), (2,'m','n'
my_list = [(1,'a','b','c'), (2,'d','e','f'), (3,'g','h','i'), (1,'j','k','l'), (2,'m','n','o'), (1,'p','q','r'), (2,'s','t','u')]
我需要在元组的子列表上拆分它,从第一项为“1”的元组开始
[(1,'a','b','c'), (2,'d','e','f'), (3,'g','h','i')]
[(1,'j','k','l'), (2,'m','n','o')]
[(1,'p','q','r'), (2,'s','t','u')]
试试这个代码。我假设在再次找到第一个字符(1)时中断。我还假设输出是一个列表
my_list = [(1,'a','b','c'), (2,'d','e','f'), (3,'g','h','i'), (1,'j','k','l'), (2,'m','n','o'), (1,'p','q','r'), (2,'s','t','u')]
ch = my_list[0][0]
all = []
st = 0
for i, t in enumerate(my_list):
if t[0] == ch:
if i != 0:
all.append(my_list[st:i])
st = i
else:
all.append(my_list[st:i])
print(all)
输出
[
[(1, 'a', 'b', 'c'), (2, 'd', 'e', 'f'), (3, 'g', 'h', 'i')],
[(1, 'j', 'k', 'l'), (2, 'm', 'n', 'o')],
[(1, 'p', 'q', 'r')]
]
试试这个代码。我假设在再次找到第一个字符(1)时中断。我还假设输出是一个列表
my_list = [(1,'a','b','c'), (2,'d','e','f'), (3,'g','h','i'), (1,'j','k','l'), (2,'m','n','o'), (1,'p','q','r'), (2,'s','t','u')]
ch = my_list[0][0]
all = []
st = 0
for i, t in enumerate(my_list):
if t[0] == ch:
if i != 0:
all.append(my_list[st:i])
st = i
else:
all.append(my_list[st:i])
print(all)
输出
[
[(1, 'a', 'b', 'c'), (2, 'd', 'e', 'f'), (3, 'g', 'h', 'i')],
[(1, 'j', 'k', 'l'), (2, 'm', 'n', 'o')],
[(1, 'p', 'q', 'r')]
]
您实际上是在计算某种“groupwhile”函数——您希望在
1
中找到的每个元组处进行拆分。这看起来非常像itertools.groupby
,如果我们保留一点点全局状态(示例中的one\u count
变量),我们就可以重新使用语言中内置的分组/聚合逻辑来获得所需的结果
import itertools
# The inner function is just so that one_count will be initialized only
# as many times as we want to call this rather than exactly once via
# some kind of global variable.
def gen_count():
def _cnt(t, one_count=[0]):
if t[0] == 1:
one_count[0] += 1
return one_count[0]
return _cnt
result = [list(g[1]) for g in itertools.groupby(my_list, key=gen_count())]
一个更传统的解决方案是迭代示例并将中间输出附加到结果集
result = []
for i, *x in my_list:
if i==1:
result.append([(i, *x)])
else:
result[-1].append((i, *x))
您实际上是在计算某种“groupwhile”函数——您希望在
1
中找到的每个元组处进行拆分。这看起来非常像itertools.groupby
,如果我们保留一点点全局状态(示例中的one\u count
变量),我们就可以重新使用语言中内置的分组/聚合逻辑来获得所需的结果
import itertools
# The inner function is just so that one_count will be initialized only
# as many times as we want to call this rather than exactly once via
# some kind of global variable.
def gen_count():
def _cnt(t, one_count=[0]):
if t[0] == 1:
one_count[0] += 1
return one_count[0]
return _cnt
result = [list(g[1]) for g in itertools.groupby(my_list, key=gen_count())]
一个更传统的解决方案是迭代示例并将中间输出附加到结果集
result = []
for i, *x in my_list:
if i==1:
result.append([(i, *x)])
else:
result[-1].append((i, *x))