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
循環可能需要被丟棄。
任何幫助表示讚賞的傢伙!
@兩位Alchemist-原因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)
你的問題的下半部分是沒有意義的,並且使整個事情不清楚。爲什麼你突然想要3個列表?什麼是'y'?假定'w'和'x'被定義爲什麼? –
我編輯了OP來澄清 – dyao