我怎样才能让它更像Python?

2024-03-29 09:28:30 发布

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

我正在做一个函数,在一个集合中找到一个最符合给定日期的字符串。我决定用一个类似CSS选择器的评分系统来做,因为它有着相同的特异性概念。你知道吗

其中一部分是计算最小分数。如果我要找一个日期(年-月-日),那么最小值是100。如果我想要一个月(只有一个月和一年),那么它是10,如果我只有一年,那么它是1:

minscore = 1
if month: minscore = 10
if day: minscore = 100

我对Python很陌生,所以我不知道所有的窍门。我怎样才能使它更(最)像Python?你知道吗


Tags: 函数字符串概念if系统选择器评分css
3条回答

您可以使用ternary expression

minscore = 100 if day else 10 if month else 1

pep-308(条件表达式):

The motivating use case was the prevalance of error-prone attempts to achieve the same effect using "and" and "or".

疏胜于密;)

minscore = 1
if month:
    minscore = 10
elif day:
    minscore = 100

PEP 8中也引用了这一点:

Compound statements (multiple statements on the same line) are generally discouraged.

Yes:

if foo == 'blah':
    do_blah_thing() do_one() do_two() do_three() 

Rather not:

if foo == 'blah': do_blah_thing() do_one(); do_two(); do_three()

我猜条件语句(即三元表达式)可能是“最具pythonic”的方法,但我认为引用Python的Zen会更好。你知道吗

坚持易读代码:

if day:
    minscore = 100
elif month:
    minscore = 10
else:
    minscore = 1

相关问题 更多 >