输入:d=[['Afiles - segments - ASegment - seg', 'Afiles - segments - ASegment - Conf', 'Afiles - segments - ASegment - alaw', 'Afiles - segments - ASegment - trim', 'Afiles - segments - ASegment - sname', 'Afiles - segments - ASegment - recog', 'Afiles - segments - ASegment - Results', 'Afiles - segments - ASegment - Literal', 'Afiles - amp', 'Afiles - errors', 'Afiles - mishit', 'Afiles - matches', 'Afiles - nomatch', 'Afiles - silence', 'Afiles - filename', 'Afiles - matchesAboveThreshold']]
mycode-
for i in d:
for j in i:
k=j.replace("Afiles - ","",1)
if((k.find(" - "))>0):
s=k.replace("segments - ASegment - ","")
print s
else:
k=j.replace("Afiles - ","",1)
print k
使用上面的代码,我得到了以下字符串,并将这些字符串附加到嵌套列表:
seg
Conf
alaw
trim
sname
recog
Results
Literal
amp
errors
mishit
matches
nomatch
silence
filename
matchesAboveThreshold
我希望我的输出为:
[['seg','Conf','alaw','trim','sname','recog','Results','Literal','amp','errors','mishit','matches','nomatch','silence','filename','matchesAboveThreshold']]
答案 0 :(得分:0)
这可以得到你想要的东西:
result = [[item.split('-')[-1].strip() for item in alist] for alist in d]
与:
相同result = []
for alist in d:
sub_list = []
for item in alist:
sub_list.append(item.split('-')[-1].strip())
result.append(sub_list)
我们将sub_list
附加到result
,因为您期望的输出是列表。
查看python的split函数。它将简化您的代码。
您也可以将代码修改为:
result = []
for i in d:
sub_list = []
for j in i:
k=j.replace("Afiles - ","",1)
if((k.find(" - "))>0):
ans=k.replace("segments - ASegment - ","")
else:
ans=j.replace("Afiles - ","",1)
sub_list.append(ans)
result.append(sub_list)
获得相同的输出
答案 1 :(得分:0)
您可以尝试使用split(delimiter)
功能:
d = [['Afiles - segments - ASegment - seg', 'Afiles - segments - ASegment - Conf', 'Afiles - segments - ASegment - alaw', 'Afiles - segments - ASegment - trim', 'Afiles - segments - ASegment - sname', 'Afiles - segments - ASegment - recog', 'Afiles - segments - ASegment - Results', 'Afiles - segments - ASegment - Literal', 'Afiles - amp', 'Afiles - errors', 'Afiles - mishit', 'Afiles - matches', 'Afiles - nomatch', 'Afiles - silence', 'Afiles - filename', 'Afiles - matchesAboveThreshold']]
result = []
for l in d:
result.append([]) # include a new list
for s in l:
result[-1].append(s.split(" - ")[-1])
print result
<强>输出:强>
[['seg', 'Conf', 'alaw', 'trim', 'sname', 'recog', 'Results', 'Literal', 'amp', 'errors', 'mishit', 'matches', 'nomatch', 'silence', 'filename', 'matchesAboveThreshold']]
备注:强>
some_list[-1]
用于访问序列的最后一个元素。 result = [[s.split(' - ')[-1] for s in l] for l in d]