英文:
How to create a new list everytime the first element of a list is repeated?
问题
如何在列表的第一个元素重复时创建一个新的列表?例如:
list1 = [2, 3, 4, 5, 2, 1, 9, 4, 7, 8, 1]
newlist1 = [2, 3, 4, 5, 2]
newlist2 = [1, 9, 4, 7, 8, 1]
英文:
How to create a new list everytime the first element of a list is repeated? For example:
list1 = [2, 3, 4, 5, 2, 1, 9, 4, 7, 8, 1]
newlist1 = [2, 3, 4, 5, 2]
newlist2 = [1, 9, 4, 7, 8, 1]
答案1
得分: 2
使用生成器的一种简单方法是创建一个列表,并在循环中向其附加元素。当满足条件时,生成子列表并重新开始。请注意,如果值的结尾与它们的开头不同,它将忽略末尾的值。如果这不是所期望的行为,您可以在循环后再次生成带有部分子列表的值:
def partition_on_first(l):
sub_list = []
for n in l:
sub_list.append(n)
if len(sub_list) > 1 and sub_list[0] == n:
yield sub_list
sub_list = []
list1 = [2, 3, 4, 5, 2, 1, 9, 4, 7, 8, 1]
list(partition_on_first(list1))
# [[2, 3, 4, 5, 2], [1, 9, 4, 7, 8, 1]]
# case with "left-overs":
list1 = [2, 3, 4, 5, 2, 1, 9, 4, 7, 8, 1, 100, 101, 102]
list(partition_on_first(list1))
# ignores last three values
# [[2, 3, 4, 5, 2], [1, 9, 4, 7, 8, 1]]
希望这对您有所帮助。
英文:
A simple way to do this is with a generator. Create a list and append elements to it in a loop. When the condition is met, yield the sublists and start again. Note, this will ignore values at the end if they don't end with the same value they start with. If that's not the desired behavior you can yield one more time with the partial sublist after the loop:
def partition_on_first(l):
sub_list = []
for n in l:
sub_list.append(n)
if len(sub_list) > 1 and sub_list[0] == n:
yield sub_list
sub_list = []
list1 = [2, 3, 4, 5, 2, 1, 9, 4, 7, 8, 1]
list(partition_on_first(list1))
# [[2, 3, 4, 5, 2], [1, 9, 4, 7, 8, 1]]
# case with "left-overs":
list1 = [2, 3, 4, 5, 2, 1, 9, 4, 7, 8, 1, 100, 101, 102]
list(partition_on_first(list1))
# ignores last three values
# [[2, 3, 4, 5, 2], [1, 9, 4, 7, 8, 1]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论