每当出现特定字符或一组字符时,我都会尝试将自己拥有的列表拆分为单个列表。
例如
Main_list = [ 'abcd 1233','cdgfh3738','hryg21','**L**','gdyrhr657','abc31637','**R**','7473hrtfgf'...]
我想打破此列表并将其保存到子列表中,只要遇到“ L”或“ R”
所需结果:
sublist_1 = ['abcd 1233','cdgfh3738','hryg21']
sublist_2 = ['gdyrhr657','abc31637']
sublist 3 = ['7473hrtfgf'...]
有内置的功能或快速的方法吗?
编辑:我不希望分隔符出现在列表中
答案 0 :(得分:2)
使用字典存储可变数量的变量。
在这种情况下,您可以使用itertools.groupby
来有效地分隔列表:
L = ['abcd 1233','cdgfh3738','hryg21','**L**',
'gdyrhr657','abc31637','**R**','7473hrtfgf']
from itertools import groupby
# define separator keys
def split_condition(x):
return x in {'**L**', '**R**'}
# define groupby object
grouper = groupby(L, key=split_condition)
# convert to dictionary via enumerate
res = dict(enumerate((list(j) for i, j in grouper if not i), 1))
print(res)
{1: ['abcd 1233', 'cdgfh3738', 'hryg21'],
2: ['gdyrhr657', 'abc31637'],
3: ['7473hrtfgf']}
答案 1 :(得分:2)
考虑使用库中许多有用的工具之一,即more_itertools.split_at
:
给出
window.addEventListener("beforeprint", beforePrint);
window.addEventListener("afterprint", afterPrint);
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
function beforePrint() {
//Resize for printing
}
function afterPrint() {
//Resize again for after printing
}
代码
import more_itertools as mit
lst = [
"abcd 1233", "cdgfh3738", "hryg21", "**L**",
"gdyrhr657", "abc31637", "**R**",
"7473hrtfgf"
]
演示
result = list(mit.split_at(lst, pred=lambda x: set(x) & {"L", "R"}))
详细信息
sublist_1, sublist_2, sublist_3 = result
sublist_1
# ['abcd 1233', 'cdgfh3738', 'hryg21']
sublist_2
# ['gdyrhr657', 'abc31637']
sublist_3
# ['7473hrtfgf']
函数在满足特殊条件的位置拆分可迭代对象。条件函数(谓词)恰好是more_itertools.split_at
函数,它等效于以下常规函数并可以替换为以下常规函数:
lambda
只要字符串def pred(x):
a = set(x)
b = {"L", "R"}
return a.intersection(b)
的字符与x
或L
相交,谓词就返回R
,并在该位置进行拆分。
通过> pip install more_itertools
在命令行中安装此软件包。
答案 2 :(得分:1)
@Polyhedronic ,您也可以尝试一下。
>>> import re
>>> Main_list = [ 'abcd 1233','cdgfh3738','hryg21','**L**','gdyrhr657','abc31637','**R**','7473hrtfgf']
>>>
>>> s = ','.join(Main_list)
>>> s
'abcd 1233,cdgfh3738,hryg21,**L**,gdyrhr657,abc31637,**R**,7473hrtfgf'
>>>
>>> items = re.split('\*\*R\*\*|\*\*L\*\*', s)
>>> items
['abcd 1233,cdgfh3738,hryg21,', ',gdyrhr657,abc31637,', ',7473hrtfgf']
>>>
>>> output = [[a for a in item.split(',') if a] for item in items]
>>> output
[['abcd 1233', 'cdgfh3738', 'hryg21'], ['gdyrhr657', 'abc31637'], ['7473hrtfgf']]
>>>
>>> sublist_1 = output[0]
>>> sublist_2 = output[1]
>>> sublist_3 = output[2]
>>>
>>> sublist_1
['abcd 1233', 'cdgfh3738', 'hryg21']
>>>
>>> sublist_2
['gdyrhr657', 'abc31637']
>>>
>>> sublist_3
['7473hrtfgf']
>>>