如何将列表转换为列表的多个子列表?
How to convert a list into multiple sublists of a list?
我有一个项目列表,我想在同一个列表中创建子列表。
我的列表看起来像这样..
lst=['(a) subp1;\n', '(A) subp1;\n', '(1) subp1;\n', '(2) subp1;\n', '(b) subp1;\n', '(i) subpb; and\n', '(ii) subpb; and\n', '(iii) subpb; and\n', '(c) subp3.\n']
if (ij) comes in pair never comes alone like(i) or (j) always (ij) and it is lower
(i) is roman
lst1=[]
for item in lst:
lst1.append(item)
我想要像
这样的东西
if item[1].islower() till next item[1].islower i need as one sublist
我的预期输出
[['(a) subp1;\n', '(A) subp1;\n', '(1) subp1;\n', '(2) subp1;\n'],
['(b) subp1;\n', '(i) subpb; and\n', '(ii) subpb; and\n', '(iii) subpb; and\n'],
['(c) subp3.\n']]
因为你还有罗马数字要计算,我会避免 .islower()
。
一个解决方案是创建一个有效分隔符的列表,当您遇到它们时,将一个子列表附加到您的列表并将项目附加到最后一个子列表:
import string
lst=['(a) subp1;\n', '(A) subp1;\n', '(1) subp1;\n', '(2) subp1;\n', '(b) subp1;\n', '(i) subpb; and\n', '(ii) subpb; and\n', '(iii) subpb; and\n', '(c) subp3.\n']
# all ascii lowercase letter, replacing 'i' with 'ij'
separators = [letter if letter != "i" else "ij" for letter in string.ascii_lowercase]
lst1=[]
for item in lst:
if item[1] in separators:
lst1.append([])
lst1[-1].append(item)
print(lst1)
输出:
[['(a) subp1;\n', '(A) subp1;\n', '(1) subp1;\n', '(2) subp1;\n'], ['(b) subp1;\n', '(i) subpb; and\n', '(ii) subpb; and\n', '(iii) subpb; and\n'], ['(c) subp3.\n']]
如果您使用的是所有罗马数字,则需要考虑所有这些数字:
i, v, x, l, c, d, m
只需将separators
中代表罗马数字的字母替换为相关的占位符
我有一个项目列表,我想在同一个列表中创建子列表。
我的列表看起来像这样..
lst=['(a) subp1;\n', '(A) subp1;\n', '(1) subp1;\n', '(2) subp1;\n', '(b) subp1;\n', '(i) subpb; and\n', '(ii) subpb; and\n', '(iii) subpb; and\n', '(c) subp3.\n']
if (ij) comes in pair never comes alone like(i) or (j) always (ij) and it is lower
(i) is roman
lst1=[]
for item in lst:
lst1.append(item)
我想要像
这样的东西if item[1].islower() till next item[1].islower i need as one sublist
我的预期输出
[['(a) subp1;\n', '(A) subp1;\n', '(1) subp1;\n', '(2) subp1;\n'],
['(b) subp1;\n', '(i) subpb; and\n', '(ii) subpb; and\n', '(iii) subpb; and\n'],
['(c) subp3.\n']]
因为你还有罗马数字要计算,我会避免 .islower()
。
一个解决方案是创建一个有效分隔符的列表,当您遇到它们时,将一个子列表附加到您的列表并将项目附加到最后一个子列表:
import string
lst=['(a) subp1;\n', '(A) subp1;\n', '(1) subp1;\n', '(2) subp1;\n', '(b) subp1;\n', '(i) subpb; and\n', '(ii) subpb; and\n', '(iii) subpb; and\n', '(c) subp3.\n']
# all ascii lowercase letter, replacing 'i' with 'ij'
separators = [letter if letter != "i" else "ij" for letter in string.ascii_lowercase]
lst1=[]
for item in lst:
if item[1] in separators:
lst1.append([])
lst1[-1].append(item)
print(lst1)
输出:
[['(a) subp1;\n', '(A) subp1;\n', '(1) subp1;\n', '(2) subp1;\n'], ['(b) subp1;\n', '(i) subpb; and\n', '(ii) subpb; and\n', '(iii) subpb; and\n'], ['(c) subp3.\n']]
如果您使用的是所有罗马数字,则需要考虑所有这些数字:
i, v, x, l, c, d, m
只需将separators
中代表罗马数字的字母替换为相关的占位符