切片与排序
推导会写了,再取「前几个 / 后几个」,以及拍平、排序。
切片
python
timeline_tail = state["timeline"][-4:]
input_text = "\n\n".join(segment["text"] for segment in segments[:2])
merge_is_last = result["timeline"][-1] == "全部片段已汇聚"js
const timelineTail = state.timeline.slice(-4)
const inputText = segments
.slice(0, 2)
.map((s) => s.text)
.join('\n\n')
const mergeIsLast = result.timeline.at(-1) === '全部片段已汇聚'| Python | JavaScript | 含义 |
|---|---|---|
a[:2] | a.slice(0, 2) | 前 2 个 |
a[-4:] | a.slice(-4) | 最后 4 个 |
a[-1] | a.at(-1) | 最后一项 |
a[1:3] | a.slice(1, 3) | 半开区间 |
切片不改原列表。JS 对照用 slice,不要用会改原数组的 splice。
双层推导(拍平)
python
actions = [
action
for result in results
for action in result["actions"]
]js
const actions = results.flatMap((result) => result.actions)双层 for:外层在前、内层在后,读成「对每个 result,再对每个 action」。
sorted 与 sum
python
results = sorted(
data.get_state("segment_results", []),
key=lambda item: item["segment_id"],
)
missing = sum(
item["status"] != "信息完整"
for item in state["final_minutes"]["actions"]
)js
const results = [...segmentResults].sort((a, b) => a.segment_id - b.segment_id)
const missing = state.final_minutes.actions.filter(
(item) => item.status !== '信息完整',
).length| Python | JavaScript |
|---|---|
sorted(arr, key=fn) | [...arr].sort(...)(sort 会改原数组) |
sum(条件 for x in xs) | True 当 1;≈ filter().length |
lambda 这里先当「一行匿名函数」用,和 JS (x) => ... 一样。下一页先处理出错和读写文件,类型放到更后面。