操纵两个列表

时间:2015-03-28 02:24:07

标签: python

我正在尝试编写代码,如果n[i+1]不等于n[i],那么xmove将为m[i+1] - m[i],如果n[i+1] }等于n[i],那么该索引处的xmove为0,而这一直持续到n[i+1]不等于n[i],然后是xmove此时是存在相等条件时第一个和最后一个m索引之间的差异。同样适用于ymove。输出将是这个

xmove = [1, 1, 0, 0, 2, 1]

ymove = [1, 1, 0, 0, 5, 1]

谢谢

m = [1, 2, 3, 4, 5, 6, 7]

n = [1, 2, 3, 3, 3, 8, 9]

xmove = []

ymove = []

first = []

Sum = []

for i in range(len(n)-1):

    if n[i+1] == n[1]:
        messi = 0
        xmove.append(messi)
        first.append(n[i])
        Sum.append(1)
        liit = sum(Sum)
        u = first[0] - liit
        xmove.append(u)
    else:
        u = n[i+1] - n[i]
        xmove.append(u)

1 个答案:

答案 0 :(得分:0)

感谢评论中的澄清 - 如下所示:

m = [1, 2, 3, 4, 5, 6, 7]
n = [1, 2, 3, 3, 3, 8, 9]

ind = range(len(n))

xeq = set()
yeq = set()

xmove = []
ymove = []
for (i,j) in zip(ind[:-1], ind[1:]):
    # Handle xmove (based on n) ------------------------------------------------
    if n[i] != n[j]:
        if not xeq:
            xe = m[j] - m[i]
        else:
            xe = m[max(xeq)] - m[min(xeq)]
            xeq.clear()
    else:
        xe = 0
        xeq.update([i,j])
    xmove.append(xe)

    # Handle ymove (based on m) ------------------------------------------------
    if m[i] != m[j]:
        if not yeq:
            ye = n[j] - n[i]
        else:
            ye = n[max(yeq)] - n[min(yeq)]
            yeq.clear()
    else:
        ye = 0
        yeq.update([i,j])
    ymove.append(ye)



print xmove, xmove == [1, 1, 0, 0, 2, 1]
print ymove, ymove == [1, 1, 0, 0, 5, 1]

输出:

[1, 1, 0, 0, 2, 1] True
[1, 1, 0, 0, 5, 1] True

或使用功能:

def get_moves(a, b):
    ind = range(len(a))
    eq = set()
    moves = []
    for (i,j) in zip(ind[:-1], ind[1:]):
        if b[i] != b[j]:
            e = a[j] - a[i] if not eq else a[max(eq)] - a[min(eq)]
            eq.clear()
        else:
            e = 0
            eq.update([i,j])
        moves.append(e)
    return moves

m = [1, 2, 3, 4, 5, 6, 7]
n = [1, 2, 3, 3, 3, 8, 9]

xmove = get_moves(m,n)
ymove = get_moves(n,m)

print xmove, xmove == [1, 1, 0, 0, 2, 1]
print ymove, ymove == [1, 1, 0, 0, 5, 1]

输出:

[1, 1, 0, 0, 2, 1] True
[1, 1, 0, 0, 5, 1] True