对象与列表
函数会写了,开始装数据。Python 的 dict ≈ JS 对象;list ≈ 数组。
字典 / 对象
| 概念 | Python | JavaScript |
|---|---|---|
| 字面量 | {"title": e.title} | { title: e.title } |
| 必有键 | e["title"] | e.title / e["title"] |
| 安全取值 | e.get("content") | e.content / e?.content |
| 带默认 | e.get("summary", "") | e.summary ?? "" |
| 嵌套安全 | e.get("meta", {}).get("title") | e.meta?.title |
| 浅拷贝 | dict(item) | { ...item } |
python
content = e.content[0].value if e.get("content") else e.get("summary", "")
title = str(entry.get("templateMaterial", {}).get("widgetTitle") or entry.get("title") or "").strip()
normalized = dict(item)js
const content = e.content ? e.content[0].value : (e.summary ?? '')
const title = String(
entry.templateMaterial?.widgetTitle || entry.title || '',
).trim()
const normalized = { ...item }易混:Python obj["key"] 没有键会 KeyError;JS 缺属性是 undefined。dict 用 .get() 更稳。
列表基础
| 概念 | Python | JavaScript |
|---|---|---|
| 空列表 | entries = [] | const entries = [] |
| 追加 | entries.append({...}) | entries.push({...}) |
| 长度 | len(entries) | entries.length |
| 拼接 | rss + kr | [...rss, ...kr] |
| 去重 | set(titles) | new Set(titles) |
| 成员 | t in titles | titles.includes(t) / set.has(t) |
| 全称 | all(...) | arr.every(...) |
| 转字符串 | str(x) | String(x) |
副作用遍历用 for;要新列表下一页用推导式。
python
for e in entries:
print(e["title"])js
entries.forEach((e) => console.log(e.title))Python 没有常用 forEach。做事用 for,收集用推导式。
dict 展开合并
{**base, "k": v} 浅拷一份再覆盖键。后面的键赢。
python
state = {**initial_base, "places": places, "city": city}js
const state = { ...initialBase, places, city }| Python | JavaScript |
|---|---|
{**base, "city": city} | { ...base, city } |
{**a, **b} | { ...a, ...b } |
和上面的 dict(item) 一样都是浅拷贝;只多了「合并 / 覆盖」。
下一页叠:字符串切开、拼回去、插值。