简体   繁体   English

为列表推导切片列表但保留切片值

[英]slicing a list for list comprehension but keeping sliced values

I would like to replace items[1] , items[2] , items[3] with a boolean value based on whether or not the value is None. 我想根据值是否为None,用布尔值替换items[1]items[2]items[3] This works but eliminates items[0] , items[4] , items[5] from the output. 这可以工作,但从输出中删除了items[0]items[4]items[5] I could insert/append the values back in, but I'm thinking there must be a way to do it in a single line. 我可以插入/追加值,但我认为必须有一种方法可以在一行中完成。

my_list = [[10,30,None,20,30,40],[10,20,None,10,30,40]]
booleans = [[1 if item is None else 0 for item in each_list[1:-2]] for each_list in my_list]
print booleans

Expected Output: 预期产出:

[[10, 0, 1, 0, 30, 40], [10, 0, 1, 0, 30, 40]]

You are close, you can use enumerate when iterating over your inner lists and test whether the indices are in a set that should be modified. 您很接近,您可以在迭代内部列表时使用enumerate ,并测试索引是否在应该修改的集合中。 This allows you to easily modify which indices should be tested by simply modifying the tests set, and doesn't require some form of slicing which is difficult to modify easily. 这允许您通过简单地修改tests集来轻松修改应该测试哪些索引,并且不需要某种形式的切片,这很难轻易修改。

my_list = [[10,30,None,20,30,40],[10,20,None,10,30,40]]
tests = {1, 2, 3}

new_list = [[v if i not in tests else 1 if v is None else 0 for i, v in enumerate(x)] 
            for x in my_list]

print(new_list)
# [[10, 0, 1, 0, 30, 40], [10, 0, 1, 0, 30, 40]]

Personally though, I wouldn't use a list comprehension in this case as it's ugly . 就个人而言,我不会在这种情况下使用列表理解,因为它很难看 The code below does exactly the same and is much more readable: 下面的代码完全相同,更具可读性:

my_list = [[10,30,None,20,30,40],[10,20,None,10,30,40]]
tests = {1, 2, 3}

for x in my_list:
    for i, v in enumerate(x):
        if i in tests:
            x[i] = 1 if v is None else 0

print(my_list)
# [[10, 0, 1, 0, 30, 40], [10, 0, 1, 0, 30, 40]]

使用嵌套列表推导:

booleans= [[l[0]]+[1 if i is None else 0 for i in l[1:4]]+l[4:] for l in my_list]

You need to add the rest of list (that you don't want to replace its elements ) to your edited sub_list : 您需要将剩余的列表(您不想替换其元素)添加到已编辑的子列表中:

>>> booleans = [each_list[0:1]+[1 if item is None else 0 for item in each_list[1:-2]]+each_list[4:] for each_list in my_list]
>>> print booleans
[[10, 0, 1, 0, 30, 40], [10, 0, 1, 0, 30, 40]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM