微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将一系列 IF 语句转换为 Pythonic 代码行?

如何解决如何将一系列 IF 语句转换为 Pythonic 代码行?

我正在努力提高我的列表理解能力。我想将以下内容转换为 Pythonic 代码行:

# Sample sentence
sample_sentence = "Once upon a time,three people walked into a bar,Once upon a time,three people walked into a bar"

# Empty list to hold words from sentence
words = []

# Empty lists to hold longest and shortest items
longest = []
shortest = []

# Pythonic method to split sentence into list of words
words = [c for c in sample_sentence.split()]

# Non-Pythonic routine to find the shortest and longest words
for i in words:
    if len(i) <= shortest_len:
        # shortest = [] # Reset list
        shortest.append(i)
    if len(i) >= longest_len:
        longest.append(i)

print(f"Shortest item: {','.join(shortest)}")
print(f"Longest item: {','.join(longest)}")

我尝试创建一个 Pythonic 版本的 非 Pythonic 例程 来查找最短和最长的单词:

shortest = [i for i in words if len(i) <= shortest_len: shortest.append(i) ]
print(shortest)
longest = [i for i in words if len(i) >= longest_len: longest.append(i)]
print(longest)

但它得到一个无效的语法错误

如何构造上述两行代码,是否可以使用单个 Pythonic 行将两者结合起来?

解决方法

不要错误地认为一切都必须是巧妙的单线。最好编写您将来能够查看并确切知道它将做什么的代码。在我看来,这是编写脚本的一种非常 Pythonic 的方式。是的,可以进行改进,但如果不需要,请不要进行优化。这个脚本是读两句话,如果是读整本书,我们可以改进。

正如评论中所说,每个人都有自己对“Pythonic”的定义和自己的格式。就我个人而言,当您的代码在做什么非常清楚时,我认为您不需要注释。例如,当您的变量名为 sample_sentence 时,您不需要注释“Sample Sentence”。

sample_sentence = "Once upon a time,three people walked into a bar,Once upon a time,three people walked into a bar"

words = sample_sentence.split()
words.sort(key=len)

short_len = len(words[0])
long_len = len(words[-1])

shortest_words = [word for word in words if len(word) == short_len]
longest_words = [word for word in words if len(word) == long_len]

print(f"Shortest item: {','.join(shortest_words)}")
print(f"Longest item: {','.join(longest_words)}")
,

在你的列表理解案例中试试这个来解决语法错误 -

shortest = [i for i in words if len(i) <= shortest_len]
print(shortest)
longest = [i for i in words if len(i) >= longest_len]
print(longest)

您也可以使用 words = [c for c in sample_sentence.split()] 代替 words = sample_sentence.split()

,

要解决 SyntaxError,您必须删除 : shortest.append(i): longest.append(i)。那么列表将如预期的那样。

是否可以使用单个 Pythonic 行将两者结合起来?

不,不可能在一行中建立两个列表。 (当然,您可以将两个列表结构放在一行中:

shortest = [i for i in words if len(i) <= shortest_len: shortest.append(i)]; longest = [i for i in words if len(i) >= longest_len: longest.append(i)]

)。但我不认为那是你的目标......

,

这是一个单行,用于查找句子中每个单词的长度并将它们从最短到最长排序:

words_len = sorted(list(set([(c,len(c)) for c in sample_sentence.split()])),key=lambda t: t[1])

或者正如我在评论中指出的那样,您可以通过这样做来达到同样的目的:

words = sorted(list(set(sample_sentence.split())),key=len)
print(f"shortest: {words[0]}\nlongest: {words[-1]}") 
,

获取最短和最长单词的替代代码:

sample_sentence = "Once upon a time,three people walked into a bar"

my_list = list(set([(token,len(token)) for token in sample_sentence.split()]))
longest_word = ','.join(i[0] for i in my_list if i[1]==max([x[1] for x in my_list]))
shortest_word = ','.join(i[0] for i in my_list if i[1]==min([x[1] for x in my_list]))
print(f"longest words: {longest_word}")
print(f"shortest words: {shortest_word}")

输出

longest words: people,walked
shortest words: a
,

首先,您需要在某处定义 shortest_lenlongest_len。你可以用这个:

shortest_len = min([len(word) for word in words])
longest_len = max([len(word) for word in words])

shortest = [word for word in words if len(word) == shortest_len]
longest = [word for word in words if len(word) == longest_len]

可以将这两行合并成

shortest,longest = [word for word in words if len(word) == shortest_len],[word for word in words if len(word) == longest_len]

如果你真的想发疯,你可以把它压缩到这个程度:

sample_sentence = "Once upon a time,three people walked into a bar"

print(f"Shortest item: {','.join([word for word in [c for c in sample_sentence.split()] if len(word) == min([len(word) for word in words])])}")
print(f"Longest item: {','.join([word for word in [c for c in sample_sentence.split()] if len(word) == max([len(word) for word in words])])}")

甚至将这两者合二为一 print 以获得单线:

sample_sentence = "Once upon a time,'.join([word for word in [c for c in sample_sentence.split()] if len(word) == min([len(word) for word in words])])}\nLongest item: {','.join([word for word in [c for c in sample_sentence.split()] if len(word) == max([len(word) for word in words])])}")

但是,正如@big_bad_bison 已经指出的那样,最短的解决方案并不总是与最佳解决方案和代码的可读性相同(对于您自己,数月或数年;或者对于其他人,如果您需要工作)在团队中或寻求帮助)更为重要。

许多单行代码完全是 Pythonic,因为它们使一行代码太长。 PEP 8 - Style Guide for Python Code (definitely suggested reading!) 保持清晰:

将所有行限制为最多 79 个字符。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?