给出清单A:
#include <stdio.h>
#include <string.h>
int main(void)
{
char line[100];
size_t size;
size = (size_t)printf("Enter text: ");
fgets(line, 100, stdin);
printf("\033[A\033[%zuC", size + strlen(line));
fputs(" <-- What a great text!", stdout);
return 0;
}
并列出B:
['cheese', 'spam', 'sausage', 'eggs']
我想从列表B中获取包含列表A中单词的字符串的代码。
即。对于像['cz', 'sp', 'sg', 'eg']
这样的字符串,我想从列表B中获取代码something about cheese
。保证输入字符串中只出现列表A中的一个项目。
如何在不检查每种情况的情况下实现这一目标?即什么是更好的方式,而不是:
cz
答案 0 :(得分: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
答案 1 :(得分:1)
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
答案 2 :(得分:1)
为什么不使用这样的东西:
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
答案 3 :(得分:0)
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