Dictionary use instead of dynamic variable names in Python

后端 未结 3 1003
不思量自难忘°
不思量自难忘° 2021-01-22 04:07

I have a long text file having truck configurations. In each line some properties of a truck is listed as a string. Each property has its own fixed width space in the string, su

3条回答
  •  不要未来只要你来
    2021-01-22 04:16

    Here's a complete solution from string to output:

    from collections import namedtuple, defaultdict
    
    # lightweight class
    Truck = namedtuple('Truck', 'weights spacings')
    
    def parse_truck(s):
        # convert to array of numbers
        numbers = [int(''.join(t)) for t in zip(s[::2], s[1::2])]
    
        # check length
        n = numbers[0]
        assert n * 2 == len(numbers)
        numbers = numbers[1:]
    
        return Truck(numbers[:n], numbers[n:])
    
    trucks = [
        parse_truck("031028331004"),
        ...
    ]
    
    # dictionary where every key contains a list by default
    trucks_by_spacing = defaultdict(list)
    
    for truck in trucks:
        # (True, False) instead of '10'
        key = tuple(space > 6 for space in truck.spacings)
        trucks_by_spacing[key].append(truck)
    
    print trucks_by_spacing
    
    print trucks_by_spacing[True, False]
    

提交回复
热议问题