8

假设我有一个字符串列表:

a = ['a', 'a', 'b', 'c', 'c', 'c', 'd']

我想列出至少连续出现两次的项目列表:

result = ['a', 'c']

我知道我必须使用 for 循环,但我不知道如何定位连续重复的项目。我该怎么做?

编辑:如果同一项目在 a 中重复两次怎么办?那么set函数就失效了

a = ['a', 'b', 'a', 'a', 'c', 'a', 'a', 'a', 'd', 'd']
result = ['a', 'a', 'd']
4

9 回答 9

7

在这里尝试itertools.groupby()

>>> from itertools import groupby,islice
>>> a = ['a', 'a', 'b', 'c', 'c', 'c', 'b']

>>> [list(g) for k,g in groupby(a)]
[['a', 'a'], ['b'], ['c', 'c', 'c'], ['b']] 

>>> [k for k,g in groupby(a) if len(list(g))>=2]
['a', 'c']

使用islice()

>>> [k for k,g in groupby(a) if len(list(islice(g,0,2)))==2]
>>> ['a', 'c']

使用zip()izip()

In [198]: set(x[0] for x in izip(a,a[1:]) if x[0]==x[1])
Out[198]: set(['a', 'c'])

In [199]: set(x[0] for x in zip(a,a[1:]) if x[0]==x[1])
Out[199]: set(['a', 'c'])

timeit结果:

from itertools import *

a='aaaabbbccccddddefgggghhhhhiiiiiijjjkkklllmnooooooppppppppqqqqqqsssstuuvv'

def grp_isl():
    [k for k,g in groupby(a) if len(list(islice(g,0,2)))==2]

def grpby():
    [k for k,g in groupby(a) if len(list(g))>=2]

def chn():
    set(x[1] for x in chain(izip(*([iter(a)] * 2)), izip(*([iter(a[1:])] * 2))) if x[0] == x[1])

def dread():
    set(a[i] for i in range(1, len(a)) if a[i] == a[i-1])

def xdread():
    set(a[i] for i in xrange(1, len(a)) if a[i] == a[i-1])

def inrow():
    inRow = []
    last = None
    for x in a:
        if last == x and (len(inRow) == 0 or inRow[-1] != x):
            inRow.append(last)
        last = x

def zipp():
    set(x[0] for x in zip(a,a[1:]) if x[0]==x[1])

def izipp():
    set(x[0] for x in izip(a,a[1:]) if x[0]==x[1])

if __name__=="__main__":
    import timeit
    print "islice",timeit.timeit("grp_isl()", setup="from __main__ import grp_isl")
    print "grpby",timeit.timeit("grpby()", setup="from __main__ import grpby")
    print "dread",timeit.timeit("dread()", setup="from __main__ import dread")
    print "xdread",timeit.timeit("xdread()", setup="from __main__ import xdread")
    print "chain",timeit.timeit("chn()", setup="from __main__ import chn")
    print "inrow",timeit.timeit("inrow()", setup="from __main__ import inrow")
    print "zip",timeit.timeit("zipp()", setup="from __main__ import zipp")
    print "izip",timeit.timeit("izipp()", setup="from __main__ import izipp")

输出:

islice 39.9123107277
grpby 30.1204478987
dread 17.8041124706
xdread 15.3691785568
chain 17.4777339702
inrow 11.8577565327           
zip 16.6348844045
izip 15.1468557105

结论:

与其他替代方案相比,Poke 的解决方案是最快的解决方案。

于 2012-10-22T22:13:13.763 回答
5

这听起来像是家庭作业,所以我将概述我将要做的事情:

  1. 迭代a,但将每个元素的索引保留在变量中。enumerate()会有用的。
  2. 在循环内部,从当前项目的索引for开始循环。while
  3. 只要下一个元素与前一个(或原始)相同,就重复循环。break在这里会有用。
  4. 计算循环重复的次数(为此您需要一些计数器变量)。
  5. result如果您的计数器变量为>=2 ,则将该项目附加到您的。
于 2012-10-22T22:13:59.223 回答
3

我的看法:

>>> a = ['a', 'a', 'b', 'c', 'c', 'c', 'd']
>>> inRow = []
>>> last = None
>>> for x in a:
        if last == x and (len(inRow) == 0 or inRow[-1] != x):
            inRow.append(last)
        last = x
>>> inRow
['a', 'c']
于 2012-10-22T22:20:05.820 回答
3

怎么样:

set([a[i] for i in range(1, len(a)) if a[i] == a[i-1]])

于 2012-10-22T23:12:29.590 回答
2

这是一个 Python one-liner,可以满足我的需求。它使用itertools包:

from itertools import chain, izip

a = "aabbbdeefggh" 

set(x[1] for x in chain(izip(*([iter(a)] * 2)), izip(*([iter(a[1:])] * 2))) if x[0] == x[1])
于 2012-10-22T22:39:17.530 回答
1

编辑后的问题要求避免使用 set(),排除大部分答案。

我想我会将花哨的单行列表理解与来自@poke 的旧循环和我创建的另一个循环进行比较:

from itertools import *

a = 'aaaabbbccccaaaaefgggghhhhhiiiiiijjjkkklllmnooooooaaaaaaaaqqqqqqsssstuuvv'

def izipp():
    return set(x[0] for x in izip(a, a[1:]) if x[0] == x[1])

def grpby():
    return [k for k,g in groupby(a) if len(list(g))>=2]

def poke():
    inRow = []
    last = None
    for x in a:
        if last == x and (len(inRow) == 0 or inRow[-1] != x):
            inRow.append(last)
        last = x
    return inRow    

def dread2():
    repeated_chars = []
    previous_char = ''
    for char in a:
        if repeated_chars and char == repeated_chars[-1]:
            continue
        if char == previous_char:
            repeated_chars.append(char)
        else:
            previous_char = char
    return repeated_chars

if __name__=="__main__":
    import timeit
    print "izip",timeit.timeit("izipp()", setup="from __main__ import izipp"),''.join(izipp())
    print "grpby",timeit.timeit("grpby()", setup="from __main__ import grpby"),''.join(grpby())
    print "poke",timeit.timeit("poke()", setup="from __main__ import poke"),''.join(poke())
    print "dread2",timeit.timeit("dread2()", setup="from __main__ import dread2"),''.join(dread2())

给我结果:

izip 13.2173779011 acbgihkjloqsuv
grpby 18.1190848351 abcaghijkloaqsuv
poke 11.8500328064 abcaghijkloaqsuv
dread2 9.0088801384 abcaghijkloaqsuv

所以一个基本的循环似乎比所有的列表理解都快,并且是 groupby 的两倍。然而,基本循环的读写更复杂,所以在大多数情况下我可能会坚持使用 groupby()。

于 2012-10-23T13:39:33.757 回答
0

这是一个正则表达式单行:

>>> mylist = ['a', 'a', 'b', 'c', 'c', 'c', 'd', 'a', 'a']
>>> results = [match[0][0] for match in re.findall(r'((\w)\2{1,})', ''.join(mylist))]
>>> results
['a', 'c', 'a']

对不起,太懒了,没时间。

于 2012-10-23T19:25:26.323 回答
0
a = ['a', 'a', 'b', 'c', 'c', 'c', 'd']
res=[]
for i in a:
    if a.count(i)>1 and i not in res:
        res.append(i)
print(res)
于 2012-10-27T03:25:40.350 回答
0

使用 enumerate 连续检查两个:

def repetitives(long_list)
  repeaters = []
  for counter,item in enumerate(long_list):
    if item == long_list[counter-1] and item not in repeaters:
      repeaters.append(item)
 return repeaters
于 2013-08-11T19:36:17.023 回答