使用 Python 从列表中提取元素
Extracting elements from list using Python
如何从此列表中提取 '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']
但其余的我不知道如何提取它
你能帮帮我吗?
您可以使用 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']]
以您的代码为基础,可以按如下方式完成。将 return 作为字母表的字符串,否则 return 作为十进制整数。
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]
如何从此列表中提取 '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']
但其余的我不知道如何提取它 你能帮帮我吗?
您可以使用 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']]
以您的代码为基础,可以按如下方式完成。将 return 作为字母表的字符串,否则 return 作为十进制整数。
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]