Compact way to assign values by slicing list in Python

后端 未结 5 1199
悲哀的现实
悲哀的现实 2020-12-01 07:04

I have the following list

bar = [\'a\',\'b\',\'c\',\'x\',\'y\',\'z\']

What I want to do is to assign 1st, 4th and 5th values of bar

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 08:10

    Yet another method:

    from itertools import compress
    
    bar = ['a','b','c','x','y','z']
    v1, v2, v3 = compress(bar, (1, 0, 0, 1, 1, 0))
    

    In addition, you can ignore length of the list and skip zeros at the end of selectors:

    v1, v2, v3 = compress(bar, (1, 0, 0, 1, 1,))
    

    https://docs.python.org/2/library/itertools.html#itertools.compress

提交回复
热议问题