Python:如果列表元素的第一项更改,如何替换选择?

时间:2013-01-30 00:09:18

标签: python list iteration alternate

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

列表:

  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

7 个答案:

答案 0 :(得分: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')

答案 1 :(得分: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

答案 2 :(得分: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']

答案 3 :(得分: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

答案 4 :(得分: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

答案 5 :(得分: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)

答案 6 :(得分: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