Is there a shorthand syntax for a sequence of throwaway variables?

后端 未结 3 1525
抹茶落季
抹茶落季 2021-01-22 07:42

Let\'s say you have a situation like this:

_, _, _, substring_1, _, substring_2 = some_string.split(\',\')

Is there a shorthand way of expressi

相关标签:
3条回答
  • 2021-01-22 08:14

    You could just use str.rsplit with a limit:

    >>> s = 'a,b,c,d,e,f'
    >>> s.rsplit(',', 3)  # i.e. split on at most three commas, from the right
    ['a,b,c', 'd', 'e', 'f']
    >>> _, d, _, f = s.rsplit(',', 3)
    >>> d
    'd'
    >>> f
    'f'
    

    If you upgrade to Python 3.x, you can use *_ to absorb an arbitrary number of elements (you'll get a SyntaxError in 2.x, though):

    >>> *_, d, _, f = s.split(',')
    >>> d
    'd'
    >>> f
    'f'
    
    0 讨论(0)
  • 2021-01-22 08:19

    Yes, if you are using Python 3 and you don't care if there are more or less than 3 entries before the last 3:

    *_, first, _, second = somestring.split(',')
    

    Otherwise, if you want the last 3 elements (regardless of how many entries the string has) you can use str.rsplit as Jon points out:

    _, first, _, second = s.rsplit(',', 3)
    

    If you want the 3rd and the 5th elements (regardless of how many elements the string has) you can use chepner's answer:

    from operator import itemgetter
    
    extract = itemgetter(3, 5)
    first, second = extract(s.split(','))
    

    Finally, if there must be six entries in the string, your best bet is to be explicit:

    KeyFields = namedtuple('KeyFields', 'first second')
    
    def extract_key_fields(s):
        data = s.split(",")
        if len(data) != 6:
            raise ValueError("Must provide six fields")
        return KeyFields(data[3], data[5])
    
    key_fields = extract_key_fields(somestring)
    key_fields.first   # d
    key_fields.second  # f
    
    0 讨论(0)
  • 2021-01-22 08:19

    Not a syntactic shortcut, but you might want to use the itemgetter function from the operator module:

    from operator import itemgetter
    my_pair = itemgetter(3, 5)
    substring_1, substring_2 = my_pair(some_string.split(','))
    

    Or, define my_pair to wrap the call to split as well:

    def my_pair(x):
        return itemgetter(3,5)(x.split(','))
    
    substring_1, substring_2 = my_pair(some_string)
    
    0 讨论(0)
提交回复
热议问题