简体   繁体   中英

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. This works but eliminates items[0] , items[4] , items[5] from the output. 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. 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.

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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