簡體   English   中英

檢查 Python 列表項是否在另一個字符串中包含一個字符串但有條件

[英]Check if a Python list item contains a string inside another string but with conditions

順便說一句,我有兩天時間學習 python 但我真的需要做那個代碼。

編輯:我想制作一個 function 來打印所有包含特定輔音(只有一個)和任意數量的人聲的單詞,但我不知道如何在這里介紹條件。

我通過輸入法制作了一個包含 4 個元素的列表(我知道我使用了不同的方式):

list = []

for x in range (4):
    words = str(input("Type a word "))
    list.append(words)

#This kinda works, but it needs to be more specific. 

matching = [s for s in list if "f" in s]
print(matching)

在我的代碼中,如果我有帶有字母“f”的單詞,我會得到一個列表,其中包含包含任意數量的“f”字母和任何其他輔音的所有單詞,但我只想要一個輔音“f”和人聲,不是其他輔音。

你可以這樣做:

words = []

for w in list:
  if 'f' in w:
    words.append(w)

print (words)

遍歷單詞並檢查您想要的字母是否在單詞中,append 它到一個新列表並打印該列表。

我這樣做了,並且確實有效。

word_list = []
consonant = input("type a consonant ") 

for _ in range(4):
words = input("Type a word: ").strip()
word_list.append(words)

accepted = set(consonant+'aeiou')

matching = [word for word in word_list if all(char in accepted for char in word)]
matching = [word for word in matching if word.count(consonant) == 1] print(matching)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM