lis中的元素组成

2024-03-29 15:13:54 发布

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

s = ['dog','cat','horse, cat, pig','horse, giraffe, dog']
x = 'giraffe'
if x in s:
    print('1')
else:
    print('0')

正在获取0。如果只输入元素所包含内容的一部分,如何让它返回1?你知道吗


Tags: in元素内容ifelsecatprintdog
2条回答

尝试:

if x in ', '.join(s).split(', '):
# ', '.join(s) returns:
# 'dog, cat, horse, cat, pig, horse, giraffe, dog' (a string)
#
# .split(', ') returns:
# ['dog', 'cat', 'horse', 'cat', 'pig', 'horse', 'giraffe', 'dog']

您的代码没有提供所需的内容,因为s包含:

'horse, giraffe, dog'

作为一根弦,所以

giraffe in ['dog', 'cat', 'horse, giraffe, dog']

将返回False。你知道吗

这也许有用

for element in s:
    if x in element: 
        print('1')
        break
else: 
   print('0')

相关问题 更多 >