Python 部分字符串映射到列表中的值
Python partial string mapping to value from list
给定列表 A:
['cheese', 'spam', 'sausage', 'eggs']
和列表 B:
['cz', 'sp', 'sg', 'eg']
我想从列表 B 中获取包含列表 A 中的单词的字符串的代码。
即对于像 something about cheese
这样的字符串,我想从列表 B 中获取代码 cz
。保证输入字符串中只出现列表 A 中的一项。
如何在不检查每个条件的情况下实现这一点? IE。什么是更好的方法而不是:
s = 'something about cheese'
if 'cheese' in s:
return 'cz'
if 'spam' in s:
return 'sp'
if 'sausage' in s:
return 'sg'
...
mapping = {
'cheese': 'cz',
'spam': 'sp',
'sausage': 'sg',
'eggs': 'eg'
}
s = 'something about cheese'
for key, value in mapping.iteritems():
if key in s:
return value
为什么不用这样的东西:
for i, key in enumerate(list_a):
if key in s:
return list_b[i]
或
for key, value in zip(list_a, list_b):
if key in s:
return value
zip
将它们放在一起并遍历 A,直到其中一个出现在字符串中。然后return对应的B.
def foo(someString, listA, listB):
for a,b in zip(listA, listB):
if a in someString:
return b
someString = "something about cheese"
listA = ['cheese', 'spam', 'sausage', 'eggs']
listB = ['cz', 'sp', 'sg', 'eg']
print(foo(someString, listA, listB)) # => cz
List_A = ['cheese', 'spam', 'sausage', 'eggs']
List_B = ['cz', 'sp', 'sg', 'eg']
s = 'something about cheese'
SplitWordsList = s.split ( " " ) # Separate the words in the sentence
for SplitWord in SplitWordsList :
if ( SplitWord in List_A ) :
return ( List_B [ List_A.index ( SplitWord ) ] )
break
给定列表 A:
['cheese', 'spam', 'sausage', 'eggs']
和列表 B:
['cz', 'sp', 'sg', 'eg']
我想从列表 B 中获取包含列表 A 中的单词的字符串的代码。
即对于像 something about cheese
这样的字符串,我想从列表 B 中获取代码 cz
。保证输入字符串中只出现列表 A 中的一项。
如何在不检查每个条件的情况下实现这一点? IE。什么是更好的方法而不是:
s = 'something about cheese'
if 'cheese' in s:
return 'cz'
if 'spam' in s:
return 'sp'
if 'sausage' in s:
return 'sg'
...
mapping = {
'cheese': 'cz',
'spam': 'sp',
'sausage': 'sg',
'eggs': 'eg'
}
s = 'something about cheese'
for key, value in mapping.iteritems():
if key in s:
return value
为什么不用这样的东西:
for i, key in enumerate(list_a):
if key in s:
return list_b[i]
或
for key, value in zip(list_a, list_b):
if key in s:
return value
zip
将它们放在一起并遍历 A,直到其中一个出现在字符串中。然后return对应的B.
def foo(someString, listA, listB):
for a,b in zip(listA, listB):
if a in someString:
return b
someString = "something about cheese"
listA = ['cheese', 'spam', 'sausage', 'eggs']
listB = ['cz', 'sp', 'sg', 'eg']
print(foo(someString, listA, listB)) # => cz
List_A = ['cheese', 'spam', 'sausage', 'eggs']
List_B = ['cz', 'sp', 'sg', 'eg']
s = 'something about cheese'
SplitWordsList = s.split ( " " ) # Separate the words in the sentence
for SplitWord in SplitWordsList :
if ( SplitWord in List_A ) :
return ( List_B [ List_A.index ( SplitWord ) ] )
break