我试图将当前列表中每个元组的最后一个元素的元组列表与某些条件进行比较。
所以,我有这样的清单:
index = [
([('T', (0, 0)), ('T', (1, 0)), ('T', (2, 0))], (1, 0)),
([('T', (0, 1)), ('M', (1, 1)), ('T', (2, 1))], (1, 1)),
([('T', (0, 2)), ('M', (1, 2)), ('T', (2, 2))], (1, 1)),
([('T', (0, 3)), ('M', (1, 3)), ('T', (2, 3))], (1, 1)),
([('T', (0, 4)), ('T', (1, 4)), ('T', (2, 4))], (1, 0))
]
预期输出为:
[
[
[('T', (0, 0)), ('T', (1, 0)), ('T', (2, 0))],
[('T', (0, 1)), ('M', (1, 1)), ('T', (2, 1))]
],
[
[('T', (0, 2)), ('M', (1, 2)), ('T', (2, 2))]
],
[
[('T', (0, 3)), ('M', (1, 3)), ('T', (2, 3))],
[('T', (0, 4)), ('T', (1, 4)), ('T', (2, 4))]
]
]
我想要做的是比较元组的每个最后元素并应用一些条件。
条件是:
Compare Position k and k+1:
1- if i found ((1,0) and (1,1)) or ((0,1) and (1,0))
or ((1,1) and (1,0)) or ((1,1) and (0,1))
=> append to a list called `f_m` and go to `Position k+2`
2- if i found (1,1) and (1,1)
=> append to a list called `f_s` and go to `Position k+1`
和0 <= i < len(index)
到目前为止,我尝试过但输出错误的是:
def get_final(index, step = 2):
k, i = 0, 0
f_m, f_s = [], []
while k < len(index):
while i <= step:
cond1 = (index[k+i][1][0] == 1 and index[k+i][1][1] == 0) and index[k+i+1][1][1] == 1
cond2 = (index[k+i][1][0] == 0 and index[k+i][1][1] == 1) and index[k+i+1][1][0] == 0
cond3 = (index[k+i][1][0] == 1 and index[k+i][1][1] == 1) and index[k+i+1][1][0] == 0
if cond1:
f_m += [index[k+i][0], index[k+i+1][0]]
i += 2
elif cond2:
f_m += [index[k+i][0], index[k+i+1][0]]
i += 2
elif cond3:
f_m += [index[k+i][0], index[k+i+1][0]]
i += 2
elif not cond1 and not cond2 and not cond3:
f_s += index[k+i][0]
i+=1
k+=i
print("f_m: ", f_m)
print("f_s: ", f_s)
我的错误输出是:
f_m: [
[('T', (0, 0)), ('T', (1, 0)), ('T', (2, 0))],
[('T', (0, 1)), ('M', (1, 1)), ('T', (2, 1))]
]
f_s: [('T', (0, 2)), ('M', (1, 2)), ('T', (2, 2))]
答案 0 :(得分:-2)
这样的东西?
index = [
([('T', (0, 0)), ('T', (1, 0)), ('T', (2, 0))], (1, 0)),
([('T', (0, 1)), ('M', (1, 1)), ('T', (2, 1))], (1, 1)),
([('T', (0, 2)), ('M', (1, 2)), ('T', (2, 2))], (1, 1)),
([('T', (0, 3)), ('M', (1, 3)), ('T', (2, 3))], (1, 1)),
([('T', (0, 4)), ('T', (1, 4)), ('T', (2, 4))], (1, 0))
]
newlist = []
i=0
while i<len(index):
if index[i][1]+index[i+1][1] in [(1,0,1,1), (0,1,1,0), (1,1,1,0), (1,1,0,1)]:
newlist.append([index[i][0]] + [index[i+1][0]])
i+=2
elif index[i][1]+index[i+1][1] == (1,1,1,1):
newlist.append([index[i][0]])
i+=1
print newlist
输出:
[
[
[('T', (0, 0)), ('T', (1, 0)), ('T', (2, 0))],
[('T', (0, 1)), ('M', (1, 1)), ('T', (2, 1))]
],
[
[('T', (0, 2)), ('M', (1, 2)), ('T', (2, 2))]
],
[
[('T', (0, 3)), ('M', (1, 3)), ('T', (2, 3))],
[('T', (0, 4)), ('T', (1, 4)), ('T', (2, 4))]
]
]