-3

我的最终名单是这样的......

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] 
4

7 回答 7

2

使用列表推导

>>> 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]
于 2012-05-07T11:05:44.620 回答
2
>>> 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)
于 2012-05-07T11:37:26.857 回答
1
([int(x[4:]) for x in l if x[:3] == 'Ram'],
 [int(x[4:]) for x in l if x[:3] == 'Sam'])
于 2012-05-07T11:05:42.200 回答
0

也可以使用正则表达式和列表推导来完成 -

>>> 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']
于 2012-05-07T11:14:09.413 回答
0

这是一个强大的解决方案。

第一阶段将输入列表转换为表单元组列表[(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']}
于 2012-05-07T11:15:41.140 回答
0

如果列表已经订购,'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]]
于 2012-05-07T12:05:15.627 回答
0
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]
于 2012-05-07T11:08:22.230 回答