2 回答

TA貢獻1895條經驗 獲得超3個贊
來自的變量any()不會超出它的范圍——它們只在它內部知道。
您只是匹配簡單的字母 - 您可以使用列表理解從列表中獲取包含此字母的所有項目:
my_list = ["abc","b","c","abracadabra"]
with_a = [ item for item in my_list if "a" in item] # or re.find ... but not needed here
# this prints all of them - you can change it to if ...: and print(with_a[0])
# to get only the first occurence
for item in with_a:
print("yes")
print(item)
輸出:
yes
abc
yes
abracadabra

TA貢獻1799條經驗 獲得超9個贊
any只告訴你是否有任何東西滿足條件,它不會讓你擁有價值。最pythonic的方法可能是這樣的:
try:
i = next(i for i in list if i == 'a')
print(i)
except StopIteration:
print('No such thing')
如果您不喜歡異常并且寧愿使用if:
i = next((i for i in list if i == 'a'), None)
if i:
print(i)
添加回答
舉報