2016-06-21 6 views
0

名前のリストと1行に複数の名前でいっぱいの.txtファイルがあります。それぞれの行について、私のリストに含まれていない名前を取り除く必要があります。例えば複数のリスト要素をpython 3行に数えます。

namelist=[Jill,Joe,Jeff,Jim] 
sampleline="Greg L,George C,Jill J,Joe F,Jeff B,Fred M" 

マイ所望の出力:私は完全に失われています

"Jill,Joe,Jeff" 

import re 

namelist = ["Jill", "Joe", "Jeff", "Jim"] 
sampleline="Greg L,George C,Jill J,Joe F,Jeff B,Fred M" 

r = set(re.split(r'\s|,', sampleline)) & set(namelist) 
final = ','.join(r) 
print(final) 
# 'Jeff,Joe,Jill' 

答えて

0

場合、これはやるべき

# braces make this a set, for theoretically faster lookup as the name "list" grows 
namelist = {'Jill', 'Joe', 'Jeff', 'Jim'} 
sampleline="Greg L,George C,Jill J,Joe F,Jeff B,Fred M" 

# Split up by commas first, then keep only the first name by splitting on whitespace 
# and dropping all but first component 
firstnames = (name.split(None, 1)[0] for name in sampleline.split(',')) 

# Iterate first names and keep the ones in the target set 
foundnames = ','.join(name for name in firstnames if name in namelist) 
# Alt: ','.join(filter(namelist.__contains__, firstnames)) 
0

単純なアプローチは、単に離れ最初の名前を分割することであり、それはターゲットセットに存在するかどうかをチェック:namelistのみ最初の名前が含まれています

関連する問題