python列表和if語句的簡單結合


將列表所有元素打印出來

cars = ['toyota', 'honda', 'mazda', 'nissan', 'mitsubishi', 'subaru', 'suzuki', 'isuzu']
for car in cars:
    new_car = car.title()
    print("Japan automobile brand: %s" % new_car)
print("\nAbove is Japan automobile brand !")

輸出

Japan automobile brand: Toyota
Japan automobile brand: Honda
Japan automobile brand: Mazda
Japan automobile brand: Nissan
Japan automobile brand: Mitsubishi
Japan automobile brand: Subaru
Japan automobile brand: Suzuki
Japan automobile brand: Isuzu

Above is Japan automobile brand !
View Code

對列表元素進行判斷

japan_cars = ['toyota', 'honda', 'mazda', 'nissan', 'mitsubishi', 'subaru', 'suzuki', 'isuzu', 'bmc']
germany_cars = 'bmc'
for car in japan_cars:
    if car != germany_cars:
        print("Japan automobile brand: " + car.title())
    else:
        print("Germany automobile brand: " + germany_cars.title())

輸出

Japan automobile brand: Toyota
Japan automobile brand: Honda
Japan automobile brand: Mazda
Japan automobile brand: Nissan
Japan automobile brand: Mitsubishi
Japan automobile brand: Subaru
Japan automobile brand: Suzuki
Japan automobile brand: Isuzu
Germany automobile brand: Bmc
View Code

 測試列表是否為空

為空

cars = []
if cars:
    print("List has tuples.")
else:
    print("List in null.")

 輸出

List in null.

不為空

cars = ['toyota']
if cars:
    print("List has tuples.")
else:
    print("List in null.")

輸出

List has tuples.

 多個列表間進行處理

查詢汽車代理商是否代理了指定品牌的汽車

agency_brands = ['toyota', 'honda', 'nissan', 'mitsubishi', 'subaru', 'suzuki', 'isuzu', 'bmc', 'audi', 'vw']
query_brands = ['ford', 'audi', 'mazda']

for query_brand in query_brands:
    if query_brand in agency_brands:
        print("Automobile brand " + query_brand + " in agency contents.")
    else:
        print("We have no " + query_brand + ".")

 輸出

We have no ford.
Automobile brand audi in agency contents.
We have no mazda.

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM