Python - 在列表中查找相同的值并将新列表组合在一起
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30293071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - Find same values in a list and group together a new list
提问by Siii
I'm stuck figuring this out and wonder if anyone could point me in the right direction...
我一直在想办法解决这个问题,想知道是否有人能指出我正确的方向......
From this list:
从这个列表:
N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
I'm trying to create:
我正在尝试创建:
L = [[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]]
Any value which is found to be the same is grouped into it's own sublist.
Here is my attempt so far, I'm thinking I should use a whileloop?
任何发现相同的值都被分组到它自己的子列表中。到目前为止,这是我的尝试,我想我应该使用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
采纳答案by Burger King
Someone mentions for N=[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 1]it will get [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5], [1]]
有人提到N=[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 1]它会得到[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5], [1]]
In other words, when numbers of the list isn't in order or it is a mess list, it's not available.
换句话说,当列表的数字不按顺序或它是一个混乱的列表时,它不可用。
So I have better answer to solve this problem.
所以我有更好的答案来解决这个问题。
from collections import Counter
N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
C = Counter(N)
print [ [k,]*v for k,v in C.items()]
回答by abarnert
You're overcomplicating this.
你把这个复杂化了。
What you want to do is: for each value, if it's the same as the last value, just append it to the list of last values; otherwise, create a new list. You can translate that English directly to Python:
您要做的是:对于每个值,如果它与最后一个值相同,则将其附加到最后一个值的列表中;否则,创建一个新列表。您可以将该英语直接翻译成 Python:
new_list = []
for value in old_list:
if new_list and new_list[-1][0] == value:
new_list[-1].append(value)
else:
new_list.append([value])
There are even simpler ways to do this if you're willing to get a bit more abstract, e.g., by using the grouping functions in itertools. But this should be easy to understand.
如果您愿意更抽象一些,还有更简单的方法可以做到这一点,例如,通过使用itertools. 但这应该很容易理解。
If you really need to do this with a whileloop, you can translate any forloop into a whileloop like this:
如果你真的需要用while循环来做到这一点,你可以将任何for循环转换成这样的while循环:
for value in iterable:
do_stuff(value)
iterator = iter(iterable)
while True:
try:
value = next(iterator)
except StopIteration:
break
do_stuff(value)
Or, if you know the iterable is a sequence, you can use a slightly simpler whileloop:
或者,如果您知道可迭代对象是一个序列,则可以使用稍微简单的while循环:
index = 0
while index < len(sequence):
value = sequence[index]
do_stuff(value)
index += 1
But both of these make your code less readable, less Pythonic, more complicated, less efficient, easier to get wrong, etc.
但这两者都会使您的代码可读性降低,Pythonic 化程度降低,更复杂,效率更低,更容易出错等。
回答by Bhargav Rao
You can use itertools.groupbyalong with a list comprehension
您可以itertools.groupby与列表理解一起使用
>>> l = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
>>> [list(v) for k,v in itertools.groupby(l)]
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]
This can be assigned to the variable Las in
这可以分配给变量,L如
L = [list(v) for k,v in itertools.groupby(l)]
回答by aldeb
Keep calm and use itertools.groupby:
保持冷静并使用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)])
Output:
输出:
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]
Side note: Prevent from using global variable when you don't needto.
旁注:防止在不需要时使用全局变量。
回答by Hunter McMillen
Another slightly different solution that doesn't rely on itertools:
另一个不依赖 itertools 的稍微不同的解决方案:
#!/usr/bin/env python
def group(items):
"""
groups a sorted list of integers into sublists based on the integer key
"""
if len(items) == 0:
return []
grouped_items = []
prev_item, rest_items = items[0], items[1:]
subgroup = [prev_item]
for item in rest_items:
if item != prev_item:
grouped_items.append(subgroup)
subgroup = []
subgroup.append(item)
prev_item = item
grouped_items.append(subgroup)
return grouped_items
print group([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5])
# [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]
回答by syviad
You can do that using numpy too:
你也可以使用 numpy 做到这一点:
import numpy as np
N = np.array([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5])
counter = np.arange(1, np.alen(N))
L = np.split(N, counter[N[1:]!=N[:-1]])
The advantage of this method is when you have another list which is related to N and you want to split it in the same way.
这种方法的优点是当您有另一个与 N 相关的列表并且您想以相同的方式拆分它时。

