使用Python从列表中提取元素

时间:2016-10-30 00:52:14

标签: python-2.7 spyder

如何从此列表中提取'1' '11''111'

T0 = ['4\t1\t\n', '0.25\t11\t\n', '0.2\t111\t\n']

提取'4''0.25''0.2'我用过这个:

def extract(T0):
    T1 = []
for i in range(0, len(T0)):
    pos = T0[i].index('\t')
T1.append(resultat[i][0: pos])
return T1
然后我得到了:

T1 = ['4','0.25','0.2']

但其余的我不知道如何提取它 你可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

您可以使用re模块和列表理解来完成此任务。

import re

# create a regular expression object
regex = re.compile(r'[0-9]{1,}\.{0,1}[0-9]{0,}') 

# assign the input list
T0 = ['4\t1\t\n', '0.25\t11\t\n', '0.2\t111\t\n']

# get a list of extractions using the regex
extractions = [x for x in [re.findall(regex, e) for e in T0]]

print extractions
# => [['4', '1'], ['0.25', '11'], ['0.2', '111']]

答案 1 :(得分:0)

使用您的代码作为基础,可以按照以下方式完成。如果是字母表,则返回字符串,否则返回十进制整数。

def extract(T0): 
    T1=[] 
    for i in range len(T0):
        tmp = T0[i].split('\t')[1]
        if tmp.isalpha():
            T1.append(tmp)
        else:
            T1.append(int(tmp))
    return T1

或者,使用列表推导

尝试下面的更紧凑的代码
def extract(T0):
    # return as string if its alphabet else return as decimal integer
    # change int function to float if wanna return as float
    tmp = [i.split('\t')[1] for i in T0]
    return [i if i.isalpha() else int(i) for i in tmp]

实施例

T0= ['X\tY\tf(x.y)\n', '0\t0\t\n', '0.1\t10\t\n', '0.2\t20\t\n', '0.3\t30\t\n']
extract(T0) # return ['Y', 0, 10, 20, 30]