[英]Function that prints string items based on first letter of each item
在Python中,我嘗試創建一個函數,該函數將基於每個字符串項目的首字母從字符串中打印項目。
def foods(lst):
if lst[0][0] == 'A':
print(lst[0])
foods(['Apples', 'Bananas', 'Yogurt', 'Zucchini', 'Grapes'])
Apples
我不太確定該怎么做,以便如果您只想基於字符串項目列表打印以A-> L或L-> Z開頭的項目。
我試圖用lst[0][1]
等添加更多if語句來檢查每個項目,但是什么也不會打印。
我還嘗試創建一條語句,例如:
if [x[0] for x in (lst)] == ['A', 'B', 'C']:
但是什么也不會打印。
任何幫助將不勝感激,希望我能明確我的問題。 謝謝。
在你們的幫助下,並回顧了以前的筆記,我發現了一種更“入門的方式”來完成我想問的問題;
def foods(lst):
for char in lst:
if char[0] > 'N':
pass
else:
print(char)
謝謝大家的幫助,不勝感激。
您可以使用列表推導和ord來執行此操作:
[x for x in lst if ord('A') <= ord(x[0]) < ord('L')]
# check first letter is between A and L
lst = foods(['Apples', 'Bananas', 'Yogurt', 'Zucchini', 'Grapes'])
print [x for x in lst if ord(A) <= ord(x[0]) < ord(L)]
# ['Apples', 'Bananas', 'Grapes']
def food(lst, start, end):
charLst = [chr(x) for x in range(ord('A'),ord('D'))]
if lst[0][0] in charLst:
print(lst[0])
foods(['Apples', 'Bananas', 'Yogurt', 'Zucchini', 'Grapes'], 'A', 'D')
蘋果香蕉
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.