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

后端 未结 3 1532
抹茶落季
抹茶落季 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: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
    

提交回复
热议问题