[英](Python) Is it possible to use a list as an argument in this way?
我想傳遞一個列表作為參數,並讓 Python 識別符合我正在尋找的標准的第一個列表項。 例如,而不是這樣:
sentence = "This is a sentence."
words = sentence.split()
for i in range(len(words)):
if words[i].startswith("a") or words[i].startswith("e") or words[i].startswith("i") or words[i].startswith("o") or words[i].startswith("u") or words[i].startswith("y"):
words[i] += "yay"
我會有這樣的事情:
sentence = "This is a sentence."
words = sentence.split()
vowels = ["a", "e", "i", "o", "u", "y"]
for i in range(len(words)):
if words[i].startswith(vowels):
words[i] += "yay"
謝謝
我會word[0] in vowels
而不是嘗試使用str.startswith
:
>>> words = "This is a sentence.".split()
>>> vowels = ["a", "e", "i", "o", "u", "y"]
>>> [w + "yay" if w[0] in vowels else w for w in words]
['This', 'isyay', 'ayay', 'sentence.']
但是您可以通過在對any
的調用中迭代vowels
來使用startswith
:
>>> [w + "yay" if any(w.startswith(v) for v in vowels) else w for w in words]
['This', 'isyay', 'ayay', 'sentence.']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.