gpt4 book ai didi

python - 如何在列表中找到相同的值并将新列表组合在一起?

转载 作者:IT老高 更新时间:2023-10-28 21:14:58 25 4
gpt4 key购买 nike

从此列表中:

N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]

我正在尝试创建:

L = [[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]]

发现相同的任何值都被分组到它自己的子列表中。到目前为止,这是我的尝试,我在想我应该使用 while 循环吗?

global n

n = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] #Sorted list
l = [] #Empty list to append values to

def compare(val):
""" This function receives index values
from the n list (n[0] etc) """

global valin
valin = val

global count
count = 0

for i in xrange(len(n)):
if valin == n[count]: # If the input value i.e. n[x] == n[iteration]
temp = valin, n[count]
l.append(temp) #append the values to a new list
count +=1
else:
count +=1


for x in xrange (len(n)):
compare(n[x]) #pass the n[x] to compare function

最佳答案

使用 itertools.groupby :

from itertools import groupby

N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]

print([list(j) for i, j in groupby(N)])

输出:

[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

旁注:当您不需要需要时,请避免使用全局变量。

关于python - 如何在列表中找到相同的值并将新列表组合在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30293071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com