• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
一泽涟漪
时光荏苒 白驹过隙
博客园    首页    新随笔    联系   管理    订阅  订阅
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.

 

 

===================来自一泽涟漪的博客,转载请标明出处 www.cnblogs.com/ilifeilong===================
posted on 2019-12-12 16:34  一泽涟漪  阅读(2911)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3