Mic*_*uts 1 python split join list-comprehension python-2.7
我以为我理解python中的分裂和连接,但它不适合我.
让我们说的价值 inp[17] = 'Potters Portland Oregon school of magic'
# a string of data I am pulling from a csv file, the data comes through just fine.
loc = inp[17]
l = loc.split(' ') # I want to split by the space
# I want to filter out all these words say they don't always
# come as "School of magic" so I cant just filter that out they
# could be mixed around at times.
locfilter = ['Potters', 'School', 'of', 'magic']
locname = ' '.join([value for value in l if l not in locfilter])
Run Code Online (Sandbox Code Playgroud)
此时我的locname变量应该只包含Portland Oregon在其中,但它仍然'Potters Portland Oregon school of magic'没有过滤掉它.
我做错了什么我觉得问题出在我的脑海里locname =.
谢谢你的帮助.
这里的问题不是你的,split或者join只是你的列表理解条件中的一个愚蠢的错误(我们所有人一直在做的那种愚蠢的错误):
locname = ' '.join([value for value in l if l not in locfilter])
Run Code Online (Sandbox Code Playgroud)
显然l永远不会locfilter.如果你解决了这个问题:
locname = ' '.join([value for value in l if value not in locfilter])
Run Code Online (Sandbox Code Playgroud)
它工作正常:
'Portland Oregon school'
Run Code Online (Sandbox Code Playgroud)
请注意,'school'它仍然是输出的一部分.那是因为'school'不在locfilter; 'School'是.如果你想匹配这些不区分大小写:
lowerfilter = [value.lower() for value in locfilter]
locname = ' '.join([value for value in l if value.lower() not in lowerfilter])
Run Code Online (Sandbox Code Playgroud)
现在:
'Portland Oregon'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |