我正在尝试使用列表解析将一个嵌套列表分成两个嵌套列表。如果不将内部列表转换为字符串,我将无法这样做,这反过来会破坏我以后访问/打印/控制值的能力。
我试过这个::
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)
因为 False
和 True
的计算结果分别为 0 和 1,所以它们可用于索引 (therest, derived)
元组。然而,许多人会认为这近乎不可读。 :)
关于python - 在包含 python 字符串的列表中提取列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34721838/