返回资讯中心
外部精选
大数据
#数据科学#机器学习

10 Python One-Liners That Will Make Your Code Cleaner and Faster

Get work done, and have seconds added back to your life since you won't be writing second, third or — *gasp!* — fourth line follow-ups to your impeccable typed line numero uno.

KDnuggetsMatthew Mayo2026/10/1 · 25 天前10 分钟阅读

以下正文同步自 KDnuggets,版权归原站所有,已转换为易读排版。

This line replaces a manual loop with a unique set of member items. It also keeps the original order, which list(set(items)) does not.

unique = list(dict.fromkeys(items))

This one-liner builds a dictionary from the items as keys, which discards repeats while keeping the order in which they first appeared (guaranteed since Python 3.7). The dictionary's keys are then converted back to a list.

This one-liner is faster and more readable than nested loops, or the common sum(nested, []) trick, which runs in quadratic time.

flat = list(itertools.chain.from_iterable(nested))

This iterates through each sublist, in lazy fashion, in sequence and collects every element into a single flattened list.

This line replaces .copy() followed by .update(), or the less readable {a, b} unpacking, with an operator whose meaning is immediately clear (Python 3.9+).

merged = defaults | overrides

A new dictionary is created with all keys from both dictionaries, and values from the right-hand dictionary win when keys conflict.

This line stops at the first match instead of scanning the whole collection. It is therefore both cleaner and faster than a flag-setting loop.

has_negative = any(x

It returns True as soon as any element satisfies the condition; False is returned if none do (and all() is the reverse check).

This line uses the walrus operator to avoid calling an expensive function twice — once to filter and once to keep the value. This exposes, and circumvents, a common hidden inefficiency in comprehensions (Python 3.8+).

results = [y for x in data if (y := transform(x)) is not None]

The one-liner applies transform to each element; it then assigns the result to y inline, and keeps only the results that aren't None.

This single decorator line can turn exponential-time recursive functions or repeated expensive computations into near-instant lookups (Python 3.9+; use @lru_cache(maxsize=None) on older versions).

@functools.cache

This code stores the return value for each unique set of arguments. Then it returns the stored result on repeat calls instead of recomputing it, for a real time savings.

This single line swaps rows and columns without index arithmetic or NumPy. This makes it an ideal tool for quick tabular reshaping.

transposed = list(zip(*matrix))

Each row is unpacked as a separate argument to zip. zip then groups the first elements of every row together, then the second elements, and so on, producing tuples of columns.

This line can replace a loop that tracks a running maximum and its key.

best = max(scores, key=scores.get)

The code iterates over the dictionary's keys, returning the key whose associated value is largest.

This replaces manual dictionary counting and sorting with an optimized, purpose-built standard library tool.

top3 = Counter(words).most_common(3)

The line counts occurrences of each element, returning a list of the three most common (item, count) pairs in descending order.

This single line removes the error-prone slicing arithmetic usually written for batching API calls or model inputs (Python 3.12+).

batches = list(itertools.batched(records, 100))

The code groups the iterable into tuples of up to 100 elements each. The final tuple holds whatever remains.

Note the simplicity of each of these entries. There isn't any magic happening; it's just in-the-trenches work, and the value is the expressiveness of each statement. I told you all the time you'd be saving right off the bat, but you didn't believe me, did you? You're welcome.

Don't forget to add this newly-acquired coding-optimization skill to your resume. You're welcome again.

Matthew Mayo (@mattmayo13) holds a master's degree in computer science and a graduate diploma in data mining. As managing editor of KDnuggets & Statology, and contributing editor at Machine Learning Mastery, Matthew aims to make complex data science concepts accessible. His professional interests include natural language processing, language models, machine learning algorithms, and exploring emerging AI. He is driven by a mission to democratize knowledge in the data science community. Matthew has been coding since he was 6 years old.

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →