Python部分字符串映射到lis中的值

2024-04-16 12:16:30 发布

您现在位置:Python中文网/ 问答频道 /正文

给定列表A:

['cheese', 'spam', 'sausage', 'eggs']

列表B:

['cz', 'sp', 'sg', 'eg']

我想从列表B中获取包含列表a中单词的字符串的代码

例如,对于像something about cheese这样的字符串,我想从列表B中获取代码cz。可以保证在输入字符串中只出现列表a中的一个项。你知道吗

如何在不检查每个条件的情况下实现这一点?也就是说,有什么更好的方法可以代替:

s = 'something about cheese'

if 'cheese' in s:
    return 'cz'
if 'spam' in s:
    return 'sp'
if 'sausage' in s:
    return 'sg'
...

Tags: 字符串代码in列表returnifczspam
3条回答

zip将它们放在一起并遍历A,直到字符串中有一个。然后返回相应的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
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

相关问题 更多 >