如果我有以下内容:

name="paula"

list=["l", "p"]

for x in list:
    print name.count(x)

>>>
1
1

如果我理解正确,则使用字符串: "paula"并确认其具有一个"l"和一个"p"字符。

但是,如果我想这样做:

#**if name has both Letters, l and p, then it is a mouse**

name="paula"

list_1=["l"]
list_2=["p"]
list_3=["l", "p"]

for y in list_3:
    if name.count(y):

   print "%s contains the letters %s and %s. %s is a mouse." % (name,w,x,name)  

#assume w and x are already defined


>>>

paula contains the letters l and p. paula is a mouse.
paula contains the letters l and p. paula is a mouse.

显然,这是行不通的。 我意识到在这段代码中,它将检查字符串"paula"中的字母"l" 然后再次运行以查看是否包含"p" 因此,两个输出而不是一个。

我认为for循环可能需要丢弃。

任何帮助是感激的家伙!

@ 2位炼金术士-3个列表的原因:

#cat, dog, mouse
#if name contains the letter "L", then it is a cat
#if name contains the Letter "P", then it is a dog
#if Name has both Letters, L and P, then it is a mouse
#if Name has no L or P, then loop the question


name="lily"
name_2="patrick"
name_3="paula"

list_1=["l"]
list_2=["p"]
list_3=["l", "p"]


for w in list_1:
    if name.count(w):
        print "%s contains the letter %s. %s is a cat." %(name,w,name)

for x in list_2:
    if name_2.count(x):
        print "%s contains the letter %s. %s is a dog." %(name_2,x,name_2)

for y in list_3:
    if name_3.count(y):
        print "%s contains the letters %s and %s. %s is a mouse." %(name_3,w,x,name_3)

===============>>#1 票数:3

我认为您最好的选择是使用组合。

name = 'paula'
seek = 'pl'

if set(seek).issubset(set(name)):
    print "{0} contains the letters '{1}'. {0} is a mouse.".format(name, seek)

>>> paula contains the letters 'pl'. paula is a mouse.

===============>>#2 票数:3

如果我理解正确,那么您想检查一下是否可以在另一个字符串中找到所有字符串列表吗?

如果是这样,您可以执行以下操作:

list3 = ["l", "p"]
name = "paula"
if all(char in name for char in list3):
    print "{0} is a mouse.".format(name)

本质上,代码的工作方式是将生成器与“ all”运算符结合使用。

代码段char in name for char in list3将遍历每个项目list3并将报告真或假值是否不是名称内部存在的字符。 这种语法称为生成器理解,与列表理解非常相似,您可以在此处了解更多信息。

简而言之, char in name for char in list3类似于以下内容:

temp = []
for char in list3:
    temp.append(char in name)
print temp

>>> [True, True]

接下来, all功能是需要的bool的列表,并返回一个内置True只有当列表中的每个元素也是True

总而言之,仅当可以在name内找到列表中的每个字符时,表达式all(char in name for char in list3)值才为True

===============>>#3 票数:1

使用any()检查列表的内容是否存在于字符串中:

name = "paula"
list_1 = ["l", "p"]
if any(word in name for word in list_1):
    print 'paula is a mouse'

  ask by dyao translate from so

未解决问题?本站智能推荐: