元素明智地检查嵌套列表

问题描述 投票:0回答:4

对多个条件检查嵌套列表元素,如果不满足条件则返回0或1。

我得检查一下

至少14岁

不能等于= 19

如果元素以4或9结尾

例如,年龄数组

[[22, 13, 31, 13],
 [17, 14, 24, 22]]

将输出数组作为

[[0, 0, 0, 0], 
 [0, 1, 1, 0]]

我试过压扁列表,然后检查每个条件,但它不起作用。

flat_list = [item for sublist in age for item in sublist]
x=14
[not x for x in flat_list]
python nested-lists elementwise-operations
4个回答
2
投票

有一个更快的numpy解决方案:

((arr >= 14) & (arr != 19) & ((arr%10 == 4) | (arr%10==9))).astype(int)

码:

import numpy as np

arr = np.array([[22, 13, 31, 13],
                [17, 14, 24, 22]])

print(((arr >= 14) & (arr != 19) & ((arr%10 == 4) | (arr%10==9))).astype(int))

# [[0 0 0 0]
#  [0 1 1 0]]

1
投票

您可以使用列表推导这样做:

somelist = [[22, 13, 31, 13],
 [17, 14, 24, 22]]

result = [[1 if (x%10==4 or x%10==9) and (x>=14 and x!=19) else 0 for x in sublist] for sublist in somelist]

result
[[0, 0, 0, 0], [0, 1, 1, 0]]

x%10将获得每个数字的最后一位数,允许直接比较。通过对这两个条件进行分组,您可以更逻辑地布置您想要做的事情,尽管这对列表理解有点麻烦。

更好的方法(可能以速度为代价)可能是使用map

def check_num(num):
    value_check = num >= 14 and num != 19
    last_num_check = num % 10 == 4 or num % 10 == 9
    return int(value_check and last_num_check)

somelist = [[22, 13, 31, 13],
 [17, 14, 24, 22]]

result = [[x for x in map(check_num, sublist)] for sublist in somelist]

result
[[0, 0, 0, 0], [0, 1, 1, 0]]

定时操作之间的差异:

列表理解

python -m timeit -s 'somelist = [[22, 13, 31, 13], [17, 14, 24, 22]]' '[[1 if (x%10==4 or x%10==9) and (x>=14 and x!=19) else 0 for x in sublist] for sublist in somelist]'
1000000 loops, best of 3: 1.35 usec per loop

地图

python -m timeit -s 'from somefunc import check_num; somelist = [[22, 13, 31, 13], [17, 14, 24, 22]]' '[[x for x in map(check_num, sublist)] for sublist in somelist]'
100000 loops, best of 3: 3.37 usec per loop

0
投票

C.Nvis对列表理解有很好的答案。您也可以使用嵌套for循环来解决此问题

def is_valid(x):
    return (x == 14) or (x%10 == 4) or (x%10 == 9)

out = []

for sublist in matrix:
    out_sublist = []
    for i in sublist:
        if (is_valid(i)):
            out_sublist.append(1)
        else:
            out_sublist.append(0)
    out.append(out_sublist)

print(out)

这些答案实际上是相同的算法。


0
投票

仅为您的示例,可以通过一些映射来完成。

验证最后一位数字是否等于数字的方法是在数字上应用模10。

my_list = [[22, 13, 31, 13],[17, 14, 24, 22]]

result_list = []
for sublist in my_list:
    result_list.append(list(map(lambda x: 1 if x % 10 == 4 and x >= 14 and x != 19 else 0, sublist)))

print(result_list)

会产生:

[[0, 0, 0, 0], [0, 1, 1, 0]]
© www.soinside.com 2019 - 2024. All rights reserved.