简体   繁体   English

学习Python拆分和联接?

[英]Learning Python Splits and Joins?

I thought I was understanding splits and joins in python but it is not working right for me. 我以为我在理解拆分并加入python,但它对我来说不合适。

lets say the value of inp[17] = 'Potters Portland Oregon school of magic' 可以说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])

At this point my locname variable should only have Portland Oregon in it, but it still has 'Potters Portland Oregon school of magic' it didn't filter out. 在这一点上,我的locname变量应该只包含Portland Oregon ,但仍然有未过滤掉的'Potters Portland Oregon school of magic' locname 'Potters Portland Oregon school of magic'

What have I done wrong I think the problem is in my locname = line. 我做错了什么我认为问题出在我的locname =行。

Thanks for any help. 谢谢你的帮助。

The problem here isn't your split or join , it's just a silly mistake in the condition in your list comprehension (the kind of silly mistake all of us make all the time): 这里的问题不是您的splitjoin ,这只是列表理解中的一个愚蠢的错误(我们所有人一直都在犯的那种愚蠢的错误):

locname = ' '.join([value for value in l if l not in locfilter])

Obviously l is never in locfilter . 显然, l从来locfilter And if you fix that: 如果您解决此问题,请执行以下操作:

locname = ' '.join([value for value in l if value not in locfilter])

It works fine: 它工作正常:

'Portland Oregon school'

Note that 'school' is still part of the output. 请注意, 'school'仍然是输出的一部分。 That's because 'school' wasn't in locfilter ; 那是因为'school'不在locfilter 'School' was. 'School'是。 If you want to match these case-insensitively: 如果要不区分大小写地匹配这些:

lowerfilter = [value.lower() for value in locfilter]
locname = ' '.join([value for value in l if value.lower() not in lowerfilter])

And now: 现在:

'Portland Oregon'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM