省略str()

时间:2016-04-10 20:49:48

标签: python python-3.x

我有一个包含主要数值的列表。我需要找到最高值,确定它包含的列表的索引,并总结该列表中的所有值。

我有这个代码可以正常工作:

results = [[213, 124, 100],
           [123.7, 444.6, 111, 12],
           [],
           [22, 11, 100, 2],
           [-1000]]

highest, row, total = -1, 0, 0
for a, b in enumerate(results):
    for i in b:
        if i > highest:
            highest = i
            row = a
            total = sum(b)

问题是我需要确保,如果其中一个值是字符串,算法不会中断。 有没有办法忽略总和中的字符串,或者我还需要迭代b并检查字符串?

1 个答案:

答案 0 :(得分:1)

您已经在遍历b;只检查每个值不是字符串然后。但是,是的,当使用sum时,你需要过滤掉字符串的值,使用生成器表达式:

for a, b in enumerate(results):
    for i in b:
        if not isinstance(i, str) and i > highest:
            highest = i
            row = a
            total = sum(i for i in b if not isinstance(i, str))

您可以反转测试并确保该值为int或float:

for a, b in enumerate(results):
    for i in b:
        if isinstance(i, (int, float)) and i > highest:
            highest = i
            row = a
            total = sum(i for i in b if isinstance(i, (int, float)))

如果您可以确保列表中仅包含数字,那么情况要好得多:

highest, row, total = 0, 0, 0
filtered_results = [[i for i in b if isinstance(i, (int, float))] for b in results]
for a, b in enumerate(filtered_results):
    for i in b:
        if i > highest:
            highest = i
            row = a
            total = sum(b)