python - 在包含 python 字符串的列表中提取列表

标签 python list nested

我正在尝试使用列表解析将一个嵌套列表分成两个嵌套列表。如果不将内部列表转换为字符串,我将无法这样做,这反过来会破坏我以后访问/打印/控制值的能力。

我试过这个::

paragraphs3 = [['Page: 2', 'Bib: Something', 'Derived:  This n that'], ['Page: 3', 'Bib: Something', 'Argument: Wouldn't you like to know?'], ...]

derived = [k for k in paragraphs3 if 'Derived:' in k]
therest = [k for k in paragraphs3 if 'Derived:' not in k]

发生的情况是整个 paragraphs3 = [] 以 therest = [] 结尾,除非我这样做:

for i in paragraphs3:
    i = str(i)
    paragraphs4.append(i)

如果我然后将 paragraphs4 提供给列表理解,我会得到两个列表,就像我想要的那样。但它们不再是嵌套列表,因为:

    for i in therest:
        g.write('\n'.join(i))
        g.write('\n\n') 

写每个 !character! in therest = [] 在单独的一行中:

'
P
a
g
e
:

2
'

因此我正在寻找一种更好的拆分段落的方法3 ... 或者也许解决方案在其他地方?我正在寻找的最终结果/输出是:

Page: 2
Bib: Something
Derived: This n that

Page: 3
Bib: Something
.
.
.

最佳答案

此代码根据子列表是否包含以 'Derived:' 开头的字符串来分隔子列表。

paragraphs3 = [['Page: 2', 'Bib: Something', 'Derived:  This n that'], ['Page: 3', 'Bib: Something', "Argument: Wouldn't you like to know?"], ]

def show(paragraphs):
    for para in paragraphs:
        print('\n'.join(para), '\n')

derived = []
therest = []

print('---input---')
show(paragraphs3)

for para in paragraphs3:
    if any(item.startswith('Derived:') for item in para):
        derived.append(para)
    else:
        therest.append(para)

print('---derived---')
show(derived)

print('---therest---')
show(therest)

输出

---input---
Page: 2
Bib: Something
Derived:  This n that 

Page: 3
Bib: Something
Argument: Wouldn't you like to know? 

---derived---
Page: 2
Bib: Something
Derived:  This n that 

---therest---
Page: 3
Bib: Something
Argument: Wouldn't you like to know? 

这段代码最重要的部分是

`any(item.startswith('Derived:') for item in para)`

这将遍历 para(当前段落)中的各个字符串,并在找到以 'Derived 开头的字符串时立即返回 True: '


FWIW,for 循环可以压缩为:

for para in paragraphs3:
    (therest, derived)[any(item.startswith('Derived:') for item in para)].append(para)

因为 FalseTrue 的计算结果分别为 0 和 1,所以它们可用于索引 (therest, derived) 元组。然而,许多人会认为这近乎不可读。 :)

关于python - 在包含 python 字符串的列表中提取列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34721838/

相关文章:

ruby-on-rails - Rails 4 中使用 gem 'closure_tree' 的嵌套注释

python - 使用 Flask/Jinja 的 HTML 动态 header (扩展)

c# - 可空列表 <> 作为输出参数

c# - 为什么 IList<>.Reverse() 不像 List<>().Reverse 那样工作

来自矩阵的选定行的 R_List

python - 在Python中构建嵌套字典从文件中逐行读取

java - 是否可以将 jasper 报告嵌入到 Python 应用程序中?

python - 如何在首页显示子页面的子页面? (鹡鸰/ Django )

python - 在具有混合值的数据框中区分 0 和 False 的简单方法

python - 获取嵌套括号中的所有文本 (Python)