1. 程式人生 > >3.5列表

3.5列表

mod ini 介紹 mob date 調用 tab eno 報錯

Pycharm使用技巧:
1.tab批量換space:
Edit-->Convert Indents--> to spaces/tabs
2.tab鍵補全
File-->power sava mode 不勾選
3批量註釋代碼
同時按住ctl+/

range介紹
Range(2)
[0,1]
實際上是一個列表
Rang(1,4)
[1,2,3]
Range(1,4,2)
[1,3]

列表
a=[”a”,”b”,”c”,”d”]
a是一個對象,才能調用方法

增刪改查
增加:

a.append("f")
print(a)
a.insert(1,"o")
print(a)

[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]

[‘a‘, ‘o‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]

查找:
切片

a=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘]
print(a[1])
print(a[1:])
print(a[1:-1])
print(a[1:4:2])
print(a[1::-1])

b
[‘b‘, ‘c‘, ‘d‘, ‘e‘]
[‘b‘, ‘c‘, ‘d‘]
[‘b‘, ‘d‘]
[‘b‘, ‘a‘]
Print(“a” in a)

a[1]="1"
print(a)

[‘a‘, ‘1‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]

a[1:3]=[2,3]
print(a)

[‘a‘, 2, 3, ‘c‘, ‘d‘, ‘e‘, ‘f‘]

刪除:
4種方法:
Remove,pop,del,clear
Pop可以返回刪除的值

a.remove("f")
print(a)
n=a.pop(1)
print(a)
print(n)
del(a[0])
print(a)
a.clear()
print(a)
print(type(a))
del a
print(a)

[‘a‘, 2, 3, ‘c‘, ‘d‘, ‘e‘]
[‘a‘, 3, ‘c‘, ‘d‘, ‘e‘]
2
[3, ‘c‘, ‘d‘, ‘e‘]
[]
<class ‘list‘>
報錯

如果要刪除的元素有多個,remove只能刪第一個元素

a=["w","a","w"]
print(a)
a.remove("w")
print(a)

[‘w‘, ‘a‘, ‘w‘]
[‘a‘, ‘w‘]

列表的其他操作:
Extend 把其他列表加入列表

print(a)
b=[4,5,6]
a.extend(b)
print(a)
print(b)

[‘a‘, 3, ‘c‘, ‘d‘, ‘e‘]
[‘a‘, 3, ‘c‘, ‘d‘, ‘e‘, 4, 5, 6]
[4, 5, 6]

Index通過內容找索引
print(a.index("a"))
0
Reverse
Sort 只支持全數字或全字符串

實例:購物車程序
輸入工資
商品列表

  1. mobile 5000
  2. book 100
  3. cup 3
  4. hair 500
    算錢,買完結賬,顯示商品和價格,余額。余額不足提示。
# -*-coding:utf-8 -*-
__date__ = ‘2018/2/6 17:56‘
__author__ = ‘xiaojiaxin‘
__file_name__ = ‘shopping_car‘

salary=int(input("input your salary:"))
counter=0
remaining_sum=salary
shopping_sum=[]
shopping={"mobile":5000,"book":128,"cup":3,"hair":70}
print(‘‘‘The product lists:
mobile:%d
book:%d
cup:%d
hair:%d
‘‘‘%(shopping["mobile"],shopping["book"],shopping["cup"],shopping["hair"]))
while True:
    shopping_car=input("enter the product‘s name:")

    if shopping_car in shopping:
        counter+=shopping[shopping_car]
        remaining_sum=salary-counter
        shopping_sum.append(shopping_car)
        flag=input("bug more?[y/n]")
        if flag=="y":
            continue
        else:
            if remaining_sum>=0:
                print("the remaining sum is %d"%remaining_sum)
                print("you have bug %s"%(shopping_sum))
                break

            else:
                print("the remaining sum is not enough to pay for it!")
                break

    else:
        print("The product do not exist!")

3.5列表