Python入门学习(二)

在迈过HelloWorld的大门后, 正式开始了解Python

变量

变量定义

当看到Python的变量定义方式时, 让我有一点意外.即没有变量的类型说明符, 也没有定义变量的标志符(如: JavaScript的var, VB的Dim)

x = 1

这样, 就定义一个变量 x 这个变量的类型, 取决于变量指向的值. 行尾不能加分号, 让我也是纠结了好一会儿, 不过还是要入乡随俗的, 慢慢习惯了就好.

数据类型

基本数据类型

基本数据类型包括 int, float, str, bool

测试基本数据类型:

i = 1
f = 2.0
s = "jack"
b = True
print("i type", type(i))
print("f type", type(f))
print("s type", type(s))
print("b type", type(b))

执行结果:

《Python入门学习(二)》

常用的数据类型

  1. list
  2. tuple
  3. set
  4. dictionary
list (数组)
arr = [1, "jack", 9.7, True]
print(arr)
print(type(arr))

执行结果:
《Python入门学习(二)》

同样我们也可以定义一个二维数组:

arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(arr[1][1]) # 5

当数组中的内容不固定时, 我们还可以动态操作 list:

arr = []
arr.append("A")
arr.append("B")
arr.append("C")
arr.insert(1, "X")
arr.remove("B")
arr.pop()
arr.pop(0)
print(arr)

append: 将在数组末尾添加元素
insert: 将在指定位置添加元素
remove: 删除指定元素
pop: 删除指定位置的元素, 如果没有指定位置, 则删除末尾元素

tuple(元组)

tuple和list非常类似,但是tuple一旦初始化就不能修改

classmates = ('Michael', 'Bob', 'Tracy')
print('classmates =', classmates)
print('classmates[0] =', classmates[0])
classmates[0] = "Jack" # TypeError: 'tuple' object does not support item assignment

但是当tuple中含有 list, set, dictionary时, 情况就不一样了

classmates = ('Michael', ["a", "b"])
classmates[1].append("c")
print('classmates =', classmates)

执行结果:

classmates = (‘Michael’, [‘a’, ‘b’, ‘c’])

看上去 classmates 改变了, 但实际上 classmates 是没有变的. classmates[1]指向的list的指针是没有变的, 改变的是指针指向的list

set(集合)

set有一个特性, 就是元素的内容是唯一的, 还有set和tuple一样, 只可以添加不可变的值

s = set([1, 2, 3]) # 初始化Set时, 只能接收list
s.add(4)
s.add((4, 5)) # set 只可以添加不可变的值
s.add((4, 5)) # 不会重复添加
s.add((4, 5, 6))
x = "ABC"
s.add(x)
x = "XYZ" # 虽然 x 改变了指针指向, 但set中原来添加的并不是变量x, 而是x所指向的"ABC"
# s.add([1, 2, 5]) # set 不能添加可变的元素
s.remove(1)
s.remove((4, 5, 6))

# s.remove(5) # KeyError: 5

print(s)

执行结果:
《Python入门学习(二)》

dictionary(字典)
dictionary = {
    "name" : "小明", 
    "age" : 23, 
    "phone":"18733774869",
    "age" : 24 # 这样是可以的, 新值会覆盖旧值, 但实际情况中这样没有意义
}
dictionary["age"] = dictionary["age"] + 1 # 修改dictionary中指定key的值
dictionary["address"] = "北京, 丰台区" # 向dictionary中添加新的元素
print(isinstance(dictionary["phone"], str))
print(isinstance(dictionary["age"], int))
print(isinstance(dictionary["name"], str))
print(dictionary["age"])
if "age" in dictionary: # 判断dictionary中, 是否存在指定的key
    print(dictionary["age"])
for key in dictionary:
    print(key, '\t => \t', dictionary[key])
print(dictionary.pop("age")) # 删除指定的key
print(dictionary.get("Age")) # None
# print(dictionary["Age"]) # KeyError: 'Age'
print(dictionary.get("Age", -1)) # -1, 若Map中没对应的key, 则返回指定的默认值
    原文作者:yuchen352416
    原文地址: https://segmentfault.com/a/1190000012791650
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞