Python:构造函数传衍生值,集合推导式的更优可读写法问询
Great question! Let's break this down and explore some cleaner, more readable set comprehension alternatives to your existing s2, s4, s5, plus a few other implementation approaches that might fit your needs better.
More Readable Set Comprehension Options
Option 1: Nested generator expression (cleaner than
s2)
Instead of cramming logic into a lambda, you can use a tiny nested generator to capture the result offun1()once, then reuse it forfun2(). This keeps the flow straightforward:s6 = {NT(1, f1, fun2(f1), 1) for _ in range(3) for f1 in (fun1(),)}The
for f1 in (fun1(),)trick runsfun1()exactly once per iteration, giving you a reusable variable without extra function definitions.Option 2: Walrus operator (Python 3.8+)
If you're on Python 3.8 or newer, the walrus operator (:=) lets you bind the result offun1()directly in the comprehension, making the logic crystal clear:s7 = {NT(1, f1, fun2(f1), 1) for _ in range(3) if (f1 := fun1())}The
ifclause here is just a hack to execute the assignment (sincerandom.random()always returns a truthy float, the condition never fails). This avoids repeating calls tofun1()and keeps everything in one line without sacrificing readability.
Other Implementation Approaches
If you're open to moving beyond set comprehensions, these options balance readability and efficiency nicely:
Generator function +
set()
Wrap the loop logic in a dedicated generator function—this makes your intent explicit and easy to modify later:def generate_nt_objects(count): for _ in range(count): f1_val = fun1() yield NT(1, f1_val, fun2(f1_val), 1) s8 = set(generate_nt_objects(3))This is just as readable as your original
s1loop, but it's more reusable (you can call the generator multiple times or iterate over it without converting to a set immediately).itertools.map+ helper function
Usemapto apply a helper function to a sequence of placeholder values (created withitertools.repeat):from itertools import repeat def build_nt(_): f1_val = fun1() return NT(1, f1_val, fun2(f1_val), 1) s9 = set(map(build_nt, repeat(None, 3)))This is a functional-style approach that keeps the NT-building logic encapsulated, similar to the generator function but with a more concise setup.
Quick Recap
- For set comprehensions, the walrus operator version (
s7) is the most readable by far, followed closely by the nested generator (s6). Both are way easier to parse thans2,s4, ors5. - If you don't need a comprehension, the generator function (
s8) is the most maintainable option—it’s clear, reusable, and matches the efficiency of your originals1loop.
内容的提问来源于stack exchange,提问作者Szymon

