python - Sorting and enumerating imported data from txt file (Python)
问题描述
guys!
I'm trying to do a movie list, with data imported from a txt file that looks like this:
"Star Wars", "Y"
"Indiana Jones", "N"
"Pulp Fiction", "N"
"Fight Club", "Y"
(with Y = watched, and N = haven't seen yet)
I'm trying to sort the list by name, so that it'll look something like:
1. Fight Club (Watched)
2. Indiana Jones (Have Not Watched Yet)
3. Pulp Fiction (Have Not Watched Yet)
4. Star Wars (Watched)
And this is what I have so far:
def sortAlphabetically():
movie_list = {}
with open('movies.txt') as f:
for line in f:
movie, watched = line.strip().split(',')
movie_list[movie.strip()] = watched.strip()
if watched.strip() == '"N"':
print(movie.strip() + " (Have Not Watched Yet)")
if watched.strip() == '"Y"':
print(movie.strip() + " (Watched)")
I found a tutorial and tried adding this code within the function to sort them:
sortedByKeyDict = sorted(movie_list.items(), key=lambda t: t[0])
return sortedByKeyDict
I also tried using from ast import literal_eval
to try and remove the quotation marks and then inserting this in the function:
for k, v in movie_list.items():
movie_list[literal_eval(k)] = v
But neither worked. What should I try next? Is it possible to remove the quotation marks? And how do I go about enumerating?
Thank you so much in advance!
解决方案
给你,这应该这样做:
filename = './movies.txt'
watched_mapping = {
'Y': 'Watched',
'N': 'Have Not Watched Yet'
}
with open(filename) as f:
content = f.readlines()
movies = []
for line in content:
name, watched = line.strip().lstrip('"').rstrip('"').split('", "')
movies.append({
'name': name,
'watched': watched
})
sorted_movies = sorted(movies, key=lambda k: k['name'])
for i, movie in enumerate(sorted_movies, 1):
print('{}. {} ({})'.format(
i,
movie['name'],
watched_mapping[movie['watched']],
))
首先,我们定义watched_mapping
哪些只是将文件中的值映射到要打印的值。
之后,我们打开文件并将其所有行读入一个content
列表。
接下来要做的是解析该列表并从中提取值(我们必须从每一行中提取电影名称以及是否已观看)。我们会将这些值保存到另一个字典列表中,每个字典都包含电影名称以及是否已观看。
这就是name, watched = line.strip().lstrip('"').rstrip('"').split('", "')
目的,它基本上从行的每一端剥离垃圾,然后在中间用垃圾分割行,返回干净name
和watched
.
接下来要做的是按name
每个字典中的值对列表进行排序:
sorted_movies = sorted(movies, key=lambda k: k['name'])
之后,我们简单地枚举排序列表(从 1 开始)并解析它以打印出所需的输出(使用 watch_mapping 打印出句子而不是简单的Y
and N
)。
输出:
1. Fight Club (Watched)
2. Indiana Jones (Have Not Watched Yet)
3. Pulp Fiction (Have Not Watched Yet)
4. Star Wars (Watched)
不区分大小写的排序更改:
sorted_movies = sorted(movies, key=lambda k: k['name'].lower())
只需将电影排序的值更改为小写名称。现在在排序时,所有名称都被视为小写。
推荐阅读
- c# - 我将如何获取进程的基地址并用它编辑该指针?
- php - 使用 nginx 将请求重写到不同的 enpoint
- python - 将表单输入作为 SQL 参数反应
- javascript - 显示没有 cv.imshow() 的 Opencv.js 矩阵
- spartacus-storefront - ASM Get cart 发出两个 HTTP 请求,但未通过身份验证标头
- c - 如何在C中将逗号添加到char数组中
- laravel - Laravel 删除一条记录的路由
- python - 如何通过随机初始化权重从头开始训练 keras.applications 中给出的模型?
- c++ - 为什么 include 语句返回一个错误,基本上表明该语言 (C++) 存在错误?
- python - 在python datetime中,为什么第一个月'January' = 1,但'Monday',一周的第一天= 0?