在列表中添加元素Python

问题描述:

under__list =[[74, 0.1423287845938018, None, None, 10, 
    1.9099604642265018, 0.5185563065935468, 1.6825659992347914, 
    3.547506695574544, 2.7789822726693023, 20051, 0, 25, None, ' >50K'], 
    [44, 0.9181229773462783, None, None, 14, 0.17973300970873787, 
    0.1644822006472492, 0.13940129449838187, 1.1252427184466018, 
    0.4357200647249191, 0, 0, 40, None, ' <=50K']] 

我有上面的列表,但我想将元素添加在一起,但跳过了None">=50"元素。在列表中添加元素Python

即使我不知道None数值在哪里,我也希望能够做到。 有什么建议吗?

for item in zip(under__list[row]): 
    under__list.append(int(sum(item[0]))) 

寻找以下的输出:

[1182, 25.2452245, None, None, 9212, 256, 2624, 25.24, 
    2532, 25, 2005252, 52, 25632, None, ' >50K'] 

这将是一个清单,加在一起的数字。

+3

请提供此输入所需的输出的一个例子。特别是不清楚你想要做什么“添加”。 – 2014-11-23 17:33:15

它看起来像你想从所有内部列表中的相同指数的项目求和。对于首先你需要使用zip*,然后在每一行的第一个项目的列表解析检查是Number类型或者简单地intfloatisinstance(x[0], (int, float)))的情况下,如果是,总结他们还使用第一项作为价值。

>>> from numbers import Number 
>>> [sum(x) if isinstance(x[0], Number) else x[0] for x in zip(*under__list)] 
[118, 1.0604517619400802, None, None, 24, 2.0896934739352395, 0.683038507240796, 1.8219672937331732, 4.672749414021146, 3.2147023373942214, 20051, 0, 65, None, ' >50K'] 

表达sum(x) if isinstance(x[0], Number) else x[0]称为conditional expression

+0

你美丽的男人......我可以吻你。非常感谢你的帮助。 :-) – 2014-11-23 20:37:37

for item in under_list: 
    item_ = filter(lambda x: x != None and x >= 50, under_list) 
    # Here compute sum of item_ and append to the right place 

写一个函数返回你所需要的:

def foo(thing): 
    try: 
     return sum(thing) 
    except TypeError: 
     return thing[0] 

map功能到zip PED under__list

>>> under__list =[[74, 0.1423287845938018, None, None, 10, 1.9099604642265018, 0.5185563065935468, 1.6825659992347914, 3.547506695574544, 2.7789822726693023, 20051, 0, 25, None,' >50K'], [44, 0.9181229773462783, None, None, 14, 0.17973300970873787, 0.1644822006472492, 0.13940129449838187, 1.1252427184466018, 0.4357200647249191, 0, 0, 40, None, ' <=50K']] 

>>> map(foo, zip(*under__list)) 
[118, 1.0604517619400802, None, None, 24, 2.0896934739352395, 0.683038507240796, 1.8219672937331732, 4.672749414021146, 3.2147023373942214, 20051, 0, 65, None, ' >50K'] 
>>>