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

时间:2025-04-15 11:14:32

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

我试过这个::

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]

会发生的是整个paragraph3 = []最终在where = [],除非我做这样的事情:

for i in paragraphs3:

i = str(i)

(i)

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

for i in therest:

('\n'.join(i))

('\n\n')

写每个!角色! inst = []在一个单独的行中:

'

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(('Derived:') for item in para):

(para)

else:

(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(('Derived:') for item in para)`

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

FWIW,for循环可以缩减为:

for para in paragraphs3:

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

因为False和True分别计算为0和1,所以它们可以用来索引(其中,派生的)元组.然而,许多人会认为这是不可读的. ????