0

因此,出于教育原因,我正在制作电影搜索 cli 应用程序。

我正在使用制表来获得一张漂亮的桌子

>>> python movies.py
Please enter a movie name: sonic
+--------+--------------------+--------+
|      1 | Sonic the Hedgehog |   2020 |
|      0 | Oasis: Supersonic  |   2016 |
|--------+--------------------+--------|
|   SlNo | Title              |   Year |
+--------+--------------------+--------+

这是我使用的代码:

# This is a wrapper for my API that scrapes Yify (yts.mx)

# Import the API
from YifyAPI.yify import search_yify as search

# Import the table
from tabulate import tabulate

# Import other utilities
import click, json


get_results = search(input('Please enter a movie name: '))
count = -1
table = []
for a in get_results:
    count += 1
    entry = [count, a['title'], a['year']]
    table.append(entry)
headers = ['SlNo', "Title", "Year"]
table = tabulate(table, headers, tablefmt='psql')
table = '\n'.join(table.split('\n')[::-1])
click.echo(table)

正如您在上面的代码中看到的那样,我有一个二维列表,我想使用每个子列表中的第 3 个项目对每部电影进行排序,这是电影发行的年份。有没有简单的 Pythonic 方法去做这个?如果需要,可以将年份转换为整数。如果可能的话,我想按最近的电影到最老的电影来排序。所以应该是降序排列。

4

1 回答 1

0

好吧,我在stackoverflow问题中挖掘了一点,找到了最适合我的答案: https ://stackoverflow.com/a/7588949/13077523

From the Python documentation wiki, I think you can do:

a = ([[1, 2, 3], [4, 5, 6], [0, 0, 1]]); 
a = sorted(a, key=lambda a_entry: a_entry[1]) 
print a
The output is:

[[[0, 0, 1], [1, 2, 3], [4, 5, 6]]]

但我所做的是:

get_results = search(input('Please enter a movie name: '))
get_results = sorted(get_results, key=lambda a_entry: a_entry['year'])
count = -1
table = []
for a in get_results:
    count += 1
    entry = [count, a['title'], a['year']]
    table.append(entry)

headers = ['SlNo', "Title", "Year"]
table = tabulate(table, headers, tablefmt='psql')
table = '\n'.join(table.split('\n')[::-1])
click.echo(table)

这对我来说非常有用!

于 2020-06-29T21:04:55.817 回答