每当列表的第一个元素重复时如何创建一个新列表?

huangapple go评论73阅读模式
英文:

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]]

huangapple
  • 本文由 发表于 2023年2月27日 09:42:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75576149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定