從你的代碼不正確indendation
除了(這可能是一個當您將其粘貼到問題中時出錯),只有一個實際問題:
car_tuple = (line[0])
這不會構成元組,但只會將line[0]
分配給car_tuple
。爲了使一個元組,你需要包括一個逗號:
car_tuple = (line[0],)
然而,這不會改變後,你將有當您試圖解開元組的問題,所以你應該只使用一個空字符串作爲第二元組項目:
car_tuple = (line[0], '')
那麼,你的代碼產生正確的結果:
Worse Manufacturer is: Ford
Cars:
1909
1958 Edsel
1971 Pinto
1995 Explorer
2000 Excursion
這爲S.通過使用更多的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)
在你的問題粘貼而不是把鏈接,這將可能是我們很快無效共享網站上的文件的一個小樣本,然後你的問題也會發生。 – bosnjak
這種從/到文件存儲和讀取數據的最佳方式是使用現有的方法。將數據保存爲JSON或YAML並從文件中讀取。 – RvdK
請注意,數據鏈接不會將未使用FileDropper註冊的人員導向文件。這不好。 –