在也有字母的列表中将负值变成 0

Turning negative values into 0s in a list that also has letters

所以这是交易。我有嵌套列表 - 列表的大部分是数字,但最后它们有用于识别列表的字母。

例如:

alist = [[0, -2, 3, 5, 10, -20, 'a'],[0, -4, 3, 30, 40, -15, 'a']]

我希望将其转化为:

alist = [[0, 0, 3, 5, 10, 0, 'a'],[0, 0, 3, 30, 40, 0, 'a']]

我知道如何使用 if 语句和 for 循环将负值转换为 0,但我不知道当列表中还存在字母时如何巧妙地执行此操作。有任何想法吗?

使用列表理解

例如:

alist = [[0, -2, 3, 5, 10, -20, 'a'],[0, -4, 3, 30, 40, -15, 'a']]
res = [[j if (isinstance(j, str) or (j > 0)) else 0 for j in i ]for i in alist]
print(res)

alist = [[0, -2, 3, 5, 10, -20, 'a'],[0, -4, 3, 30, 40, -15, 'a']]
res = []

for i in alist:
    temp = []
    for j in i:
        if isinstance(j, str) or (j > 0):
            temp.append(j)
        else:
            temp.append(0)
    res.append(temp)

print(res)

输出:

[[0, 0, 3, 5, 10, 0, 'a'], [0, 0, 3, 30, 40, 0, 'a']]

注:

  • 使用isinstance检查对象。