1

我找不到解决这个简单问题的算法:

一个列表:

  lista:  [[1,a],[1,b],[1,a],[2,s],[2,r],[3,e],[3,k],[3,t],[3,y]....]

我正在迭代这个列表,对于内部列表的第一项与下一个迭代相同的迭代,在 x 和 y 之间交替

[1,a] --> x
[1,b] --> x
[1,a] --> x
[2,s] --> y
[2,r] --> y
[3,e] --> x
[3,k] --> x
[3,t] --> x
[3,y] --> x
4

7 回答 7

3
lista = [[1,'a'],[1,'b'],[1,'a'],[2,'s'],[2,'r'],[3,'e'],[3,'k'],[3,'t'],[3,'y']]

>>> last_a = None
>>> toggle = 'y'
>>> for a, b in lista:
...     if last_a != a:
...         toggle = 'x' if toggle != 'x' else 'y'
...         last_a = a
...     print(a, b, toggle)
... 
(1, 'a', 'x')
(1, 'b', 'x')
(1, 'a', 'x')
(2, 's', 'y')
(2, 'r', 'y')
(3, 'e', 'x')
(3, 'k', 'x')
(3, 't', 'x')
(3, 'y', 'x')
于 2013-01-30T00:17:50.240 回答
2

所以,可能有更有效的方法可以做到这一点,但我喜欢使用 itertools 的任何借口!

from itertools import cycle

lista = [[1, 'x'], [1, 'x'], [1, 'x'], [2, 'x'], [2, 'x'], [3, 'x'], [3, 'x'], [3, 'x'], [3, 'x']]
r = cycle(['x','y'])

last = None
for first, second in lista:
  current = first
  if current != last:
    output = r.next()
  last = current
  print output
于 2013-01-30T00:26:38.537 回答
2

另一种itertools方法:

>>> from itertools import chain, cycle, groupby
>>> c = cycle('xy')
>>> grouped = groupby(lista, lambda x: x[0])
>>> xy = (next(c)*len(list(g)) for _, g in grouped)
>>> list(chain(*xy))
['x', 'x', 'x', 'y', 'y', 'x', 'x', 'x', 'x']
于 2013-01-30T00:44:08.570 回答
1

这是一个有趣的方法:

lista = [[1,'a'],[1,'b'],[1,'a'],[2,'s'],[2,'r'],[3,'e'],[3,'k'],[3,'t'],[3,'y']]
def function(acc,val):
    if acc[0] != val[0]:
        print acc[1]
        return (val[0],acc[2],acc[1])
    else:
        print acc[2]
        return acc
reduce(function,lista,(lista[0][0],'y','x'))

打印:

x
x
x
y
y
x
x
x
x
于 2013-01-30T00:41:19.377 回答
1
import itertools as it
import operator as op

one, other = 'x', 'y'
for k, g in it.groupby(lista, op.itemgetter(0)):
    for e in g:
        print e, one
    one, other = other, one

印刷

[1, 'a'] x
[1, 'b'] x
[1, 'a'] x
[2, 's'] y
[2, 'r'] y
[3, 'e'] x
[3, 'k'] x
[3, 't'] x
[3, 'y'] x
于 2013-01-30T00:46:08.387 回答
0

这会打印 x 和 y,我不确定您想对列表中的实际项目做什么。

a = [[1, "a"],[1,"b"],[1, "a"],[2, "s"],[2, "r"],[3, "e"],[3, "k"],[3, "t"],[3, "y"]]

def alternate(lst):
    current = lst[0][0]
    swap_vals = {"x": "y", "y": "x"}
    val = "x"
    print(val)
    for i in lst[1:]:
        next = i[0]
        if not current == next:
            val = swap_vals[val]
            current = next
        print(val)

alternate(a)
于 2013-01-30T00:17:16.550 回答
0

又快又脏:

first = lista[0][0]
toprint = 'x'

print toprint

for i in range(len(lista)-1):
    new = lista[i+1][0]
    if first != new:
        toprint = 'y' if toprint != 'y' else 'x'
        first = new
    print toprint
于 2013-01-30T00:25:06.533 回答