我想确定第一个元素或第二个元素是否匹配3 我想将元组附加到mytuple_with_3。
mytuple=[(1,3),(4,9),(3,8)]
mytuple_with_3 = []
c = 0
for x in mytuple:
if x[0][c] == 3 or x[c][1] == 3:
mytuple_with_3.append(x)
c += 1
结果显示显示(1,3)和(3,8)
答案 0 :(得分:1)
使用此列表理解:
mytuple_with_3 = [i for i in mytuple if 3 in i]
>>> mytuple_with_3
[(1, 3), (3, 8)]
要将其限制为仅前两个元素,请使用:
mytuple_with_3 = [i for i in mytuple if 3 in i[:2]]