我的最终名单是这样的......
lst = ['Ram:50', 'Ram:80', 'Ram:90', 'Ram:20', 'Sam:40', 'Sam:70', 'Sam:80']
如何将所有 Ram 分离到一个列表中,并将所有 Sam 分离到 Python 中的另一个列表中。
例子:
[50,80,90,20]
[40,70,80]
使用列表推导:
>>> l = ['Ram:50', 'Ram:80', 'Ram:90','Ram:20', 'Sam:40', 'Sam:70', 'Sam:80']
>>> [int(x[4:]) for x in l if x.startswith('Ram:')]
[50, 80, 90, 20]
>>> [int(x[4:]) for x in l if x.startswith('Sam:')]
[40, 70, 80]
>>> lis = ['Ram:50', 'Ram:80', 'Ram:90','Ram:20', 'Sam:40', 'Sam:70', 'Sam:80']
>>> D = {'Ram':[], 'Sam':[]}
>>> for k,v in (x.partition(':')[::2] for x in lis):
... D[k].append(v)
...
>>> D['Ram']
['50', '80', '90', '20']
>>> D['Sam']
['40', '70', '80']
稍微高级一点是像这样初始化 D
D = collections.defaultdict(list)
([int(x[4:]) for x in l if x[:3] == 'Ram'],
[int(x[4:]) for x in l if x[:3] == 'Sam'])
也可以使用正则表达式和列表推导来完成 -
>>> list = ['Ram:50', 'Ram:80', 'Ram:90', 'Ram:20', 'Sam:40', 'Sam:70', 'Sam:80']
>>> [re.findall(r'[0-9]*$',s)[0] for s in list if 'Ram' in s]
['50', '80', '90', '20']
>>> [re.findall(r'[0-9]*$',s)[0] for s in list if 'Sam' in s]
['40', '70', '80']
这是一个强大的解决方案。
第一阶段将输入列表转换为表单元组列表[(key,value),(key,value)...]
。该map
操作在此处使用 split 函数进行此转换。
l = ['Ram:50', 'Ram:80', 'Ram:90', 'Ram:20', 'Sam:40', 'Sam:70', 'Sam:80']
def split( input ):
sp = input.split(":")
return (sp[0], sp[1])
l2 = map(split, l)
print l2
#[('Ram', '50'), ('Ram', '80'), ('Ram', '90'), ('Ram', '20'), ('Sam', '40'), ('Sam', '70'), ('Sam', '80')]
第二阶段迭代这样的列表并填充store
字典。如果键不存在,它会创建一个映射到键的列表(一个元素)。否则它会添加到该列表中
store = {}
for i in l2:
key, value = i[0], i[1]
if key not in store.keys():
store[key] = [value]
else:
store[key].append(value)
print store
#{'Ram': ['50', '80', '90', '20'], 'Sam': ['40', '70', '80']}
如果列表已经订购,'ram'
那么'sam'
你可以这样做
>>> from itertools import groupby
>>> from operator import itemgetter
>>> lst = ['Ram:50', 'Ram:80', 'Ram:90', 'Ram:20', 'Sam:40', 'Sam:70', 'Sam:80']
>>> [[int(y) for x,y in v] for k,v in groupby((el.split(':') for el in lst),itemgetter(0))]
[[50, 80, 90, 20], [40, 70, 80]]
Ram = map(lambda y: int(y[y.find(":")+1:]), filter(lambda x: x[:x.find(":")] == "Ram", lst))
我刚才看到 root45 的解决方案是类似的,但更容易。
一天后回来总结常识:
for name in ('Ram', 'Sam'):
globals()[name] = [int(x[x.find(":")+1:]) for x in lst if x[:x.find(":")] == name]