python - 解释 "[c for c in cEdges if secString in c[0]]"

标签 python syntax list-comprehension

我试图在程序的前面找到一个错误,但被要求解释这部分代码中发生了什么。下面是代码和我认为它在做什么,但在某些方面不清楚。如果能帮助理解,我们将不胜感激。

for title in titles:
    secString = 'sec_%02d' % (title)
    titleCitations = [c for c in cEdges if secString in c[0]]
    intraCitations = [c for c in titleCitations if secString in c[1]]
    print title, len(titleCitations), len(intraCitations), len(titleCitations) - len(intraCitations)

首先,secString 获取关于标题的 'sec_%02d' 的剩余部分(我认为这只是找到所有引用标题的字符串?)。然后它会创建一个列表 titlecitations。

虽然我对括号中的部分感到困惑。如果我理解正确,它采用 cEdge,我认为它只是来自给定美国法律代码引用的一对数字列表,即 26 USC 501 变成 (26, 501),并询问 secString 在 c 中是否有值[0]现货。

(这是我感到困惑的地方;我猜测 c[0] 点可能对应于上面示例中的 26,而 c[1] 对应于 501?当然我什至不确定我是否我正确理解了 c 部分。)

如果 c[0] 位置已满,则将其放入 titlecitations。然后创建引文列表。此列表查看 titlecitations 列表,并询问 secString 中是否填充了 c[1],如果是,则将其放入此列表中。

我知道有些东西有问题,因为 titlecitations 和 intracitations 似乎是同一个列表。

最佳答案

secString = 'sec_%02d' % (title)

字符串上的 % 运算符不是模数,它是一个格式化运算符,其行为类似于 C 的 printf()。 %02d 是格式化代码,将title 格式化为两位数。如果 title 只有一位数字,则用 0 填充它(例如 9 变为 09)。

(This is where I get confused; I am guessing that the c[0] spot maybe corresponds to the 26 in the above example and c[1] would correspond to the 501? Of course I am not even sure if I am understanding the c part correctly.)

没错。

titleCitations = [c for c in cEdges if secString in c[0]]

这将搜索 cEdges 中的项目并找到标题包含字符串 sec_XY 的项目,其中 XY 是之前的两位数。

intraCitations = [c for c in titleCitations if secString in c[1]]

现在它搜索我们在上一步中找到的东西,再次搜索子字符串 sec_XY

最终结果是 intraCitations 包含来自 cEdges 的所有项目的列表,其中第一个和第二个项目都包含子字符串 sec_XY .

关于python - 解释 "[c for c in cEdges if secString in c[0]]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12926302/

相关文章:

python - 拆分关于 Pandas 时间间隔的系列?

angularjs - 注入(inject) restangular 时出错

C# 基础知识的挣扎

haskell - 学习 haskell : Making a function that returns a list of elements that only appear once

python - 使用 Python 记录器记录到文件和标准错误

python - FFmpeg "piping"不适用于 mp4 文件?

python - 从字典列表理解中返回 True 或 False

带有 if else 条件的 Python 列表理解

python - 有没有一种方法可以根据特定值过滤数据框,同时使用 Pandas 保留唯一标识符的所有其他值?

c - 如何理解 "typedef int (xxx)(int yyy);"?