• list基本操作_2


    创建数字列表

    for value in range(1,5):
        print(value,end=" ")#1 2 3 4
    print()
    #使用range可以生成一个指定范围的数字集合
    numbers = list(range(2,7))
    print(numbers)#[2, 3, 4, 5, 6]
    #使用range也可以指定步长来生成数字集合
    numbers = list(range(2,10,2))
    print(numbers)#[2, 4, 6, 8]步长是2
    #使用**2来实现一个数的平方
    lst = list()
    for value in range(1,11):
        lst.append(value**2)
    print(lst)#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    #对数字列表进行简单地统计计算
    lst = list()
    for value in range(1,11):
        lst.append(value**2)
    print(min(lst))#1
    print(max(lst))#100
    print(sum(lst))#385
    #利用解析来创建列表,将for循环和平方写成一行
    lst = list([value ** 2 for value in range(1,11)])
    print(lst) #[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    #列表的切片
    lst = list(value ** 2 for value in range(1,11))#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    print(lst[2:5]) #[9, 16, 25],从索引值2开始,打印到索引值位4的部分
    print(lst[:5]) #[1, 4, 9, 16, 25] 默认是从索引值0开始的
    print(lst[2:]) #[9, 16, 25, 36, 49, 64, 81, 100]默认是打到最后
    #负数索引返回距离列表相应距离的元素
    print(lst[-3:]) #[64, 81, 100]
    print(lst[:-3]) #[1, 4, 9, 16, 25, 36, 49]
    
    #如果要遍历部分切片,可以在for循环内部写上切片
    for value in lst[2:9:2]:
        print(value,end=" ")
    #列表的复制,切记不要直接使用myFrinedFoof = myFood
    myFood = ["pizza","falafel","carrot cake"]
    myFrinedFoof = myFood[:]
    
    myFood.append("apple") #['pizza', 'falafel', 'carrot cake', 'apple']
    myFrinedFoof.append("banana") #['pizza', 'falafel', 'carrot cake', 'banana']
    print(myFrinedFoof)
    print(myFood)
    #if和列表的结合应用
    avaliable_toppings = ["mushroom","oLive","green peppers",
                          "pepperoni","pineapple","extra cheese"]
    requested_toppings = ["mushroom","french fries","extra cheese"]
    for requested_topping in requested_toppings:
        if requested_topping in avaliable_toppings:
            print("Adding " + requested_topping + ".")
        else:
            print("Sorry , We don't have " + requested_topping + "." )
  • 相关阅读:
    SettingsProvider 它SettingsCache
    14、Cocos2dx 3.0三,找一个小游戏开发Scene and Layer:游戏梦想
    open-flash-chart2各种效果
    Android使用surface直接显示yuv数据(三)
    LeetCode:Populating Next Right Pointers in Each Node
    zoj 3203 Light Bulb,三分之二的基本问题
    POJ 2485 Highways
    Leetcode
    android音乐柱状频谱实现
    Android自定义控件实战——水流波动效果的实现WaveView
  • 原文地址:https://www.cnblogs.com/boost/p/13259944.html
Copyright © 2020-2023  润新知