添加列表元素

时间:2012-05-07 10:56:31

标签: python list

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

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] 

7 个答案:

答案 0 :(得分:2)

使用list comprehensions

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

答案 1 :(得分: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)

答案 2 :(得分:1)

([int(x[4:]) for x in l if x[:3] == 'Ram'],
 [int(x[4:]) for x in l if x[:3] == 'Sam'])

答案 3 :(得分: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]

答案 4 :(得分: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']

答案 5 :(得分: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']}

答案 6 :(得分: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]]