Python从fi创建字典

2024-09-24 22:27:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python代码,它没有读我想要它读的东西。 对于最差的车,福特应该是最差的车,但我一直得到雪佛兰ssr的结果有什么帮助吗?在

这是我正在处理的文件的格式:

1899 Horsey Horseless
1909 Ford Model T
1911 Overland OctoAuto
1913 Scripps-Booth Bi-Autogo
1920 Briggs and Stratton Flyer
1933 Fuller Dymaxion
1934 Chrysler/Desoto Airflow
1949 Crosley Hotshot
1956 Renault Dauphine
1957 King Midget Model III

这是我的密码:

^{pr2}$

Tags: 文件代码model格式bifordssrbooth
1条回答
网友
1楼 · 发布于 2024-09-24 22:27:04

除了代码的不正确的索引(这可能是您粘贴到问题中时的一个错误),它只有一个真正的问题:

car_tuple = (line[0])

这不会生成一个元组,只会将line[0]分配给car_tuple。要使其成为元组,需要包含逗号:

^{pr2}$

但是,这不会改变您以后在尝试解包元组时遇到的问题,因此您应该只使用空字符串作为第二个元组项:

car_tuple = (line[0], '')

然后,您的代码将得到正确的结果:

Worse Manufacturer is:  Ford
Cars:
1909
1958 Edsel
1971 Pinto
1995 Explorer
2000 Excursion

也就是说,您可以通过使用更多的Python技巧来简化这一切。这是我的8行解决方案,加上注释,以便您了解情况:

# We’re going to use `defaultdict` to handle the whole “when there is
# already an element in the dictionay, append to the list, otherwise
# create a new entry with a single list item” thing. `defaultdict` just
# allows us to append without having to manually initialize new keys.
from collections import defaultdict

# Files should always be opened with the `with` statement, to ensure
# that they are closed correctly afterwards. Since we’re reading, we
# don’t need to specify the open mode ('r' is the default).
with open('cars.txt') as f:
    # We initialize our dictionary as a defaultdict, where each item
    # is automatically initialized with an empty list.
    cars = defaultdict(list)

    for line in f:
        # We put strip and split in a single line. Since we always
        # get at least two values from your file format, we can just
        # unpack the values directly. We collect additional unpacked
        # values (so index 2 or above) in a list called `rest` (the
        # star symbol does that). That list may be empty, or not.
        year, manufacturer, *rest = line.strip().split()

        # We just append (because it’s a defaultdict, we don’t need
        # to initialize it) to the list of the manufacturer a tuple
        # with the unpacked year, and the joined values of the rest.
        cars[manufacturer].append((year, ' '.join(rest)))

# Now that we collected our cars dictionary, we want to find the
# manufacturer that has the highest number of cars. Since `cars` maps
# the key manufacturer to the a list of cars (car tuples actually), we
# essentially want to get the dictionary item with the maximum length
# in the item value. We use the built-in `max` function with a custom
# key function for this.
# `cars.items()` returns a sequence of key/value tuples of the
# dictionary. We want to get the maximum value of those key/value
# tuples, and as a metric for “maximum value” we use a function that
# takes this tuple `(manufacturer, listOfCarTuples)` and returns the
# length of that `listOfCarTuples`. So in the key function, `x` is that
# tuple, so `x[1]` is the list of car tuples. So the length of that list
# is the metric of the current dictionary item which we want to get the
# maximum from.
worst = max(cars.items(), key=lambda x: len(x[1]))

# `worst` is now `(manufacturer, listOfCarTuples)` where
# `len(listOfCarTuples)` has the maximum value.
print(worst)

相关问题 更多 >