繁体   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