我有一个二维整数数组:
[[26, 9, 24, 13],
[16, 14, 39, 29]]
我需要选择数字> = 14,以9或4结尾,而不是39。如果满足条件,则返回1,否则返回0,即
[[0, 0, 1,0],
[0,0,0,1]]
已更新:Tomothy32建议的代码
result = result = [[int(x >= 14 and x % 10 in (4, 9) and x != 19) for x in sl] for sl in X]
另一种嵌套循环方法
def test(X):
out = [[0]*len(X[0]) for _ in range(len(X))]
for i in range(len(X)):
for j in range(len(X[i])):
check = X[i][j]
if check>=14 and check%5==4 and check!=39:
out[i][j] = 2
return out
答案 0 :(得分:0)
您可以使用列表理解:
x = [[26, 9, 43, 13],
[16, 14, 39, 29]]
result = [[int(x >= 14 and x % 10 == 9 and x != 39) for x in sl] for sl in x]
print(result)
# [[0, 0, 0, 0], [0, 0, 0, 1]]
要获取最后一位,请使用余数/模运算符。
答案 1 :(得分:0)
更改此语句:
if element >=14 and element !=39:
到
if element >=14 and element !=39 and element%10==9: