python - 数据类型

远观山色年年依然常青,近看人情朝朝不如往日

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
六个标准的数类型:
number,string,list(列表),tuple(元组),set(集合),dictionary
"""

"""
Number:
int , float , bool , complex
"""
a,b,c = 20,6.6,True
print(type(a),type(b),type(c))
print(isinstance(a,int))

print(2/4) # 得到浮点数
print(2//4) # 得到整数
print(17%3) # 取余
print(2**5) # 乘方

"""
String
不能改变字符串,向索引位置重新赋值会导致错误, word[0] = 'm'
"""
word = 'python'
print(word[0],word[5])
print(word[-6],word[-1])

"""
List:
列表写在方括号之间【】,用逗号分隔开的元素列表
和字符串一样,可以被索引和截取(一个新的列表)
和字符串不同的是,列表中的元素可以被改变
"""
list = [1,2,3,'abc']

print(list[2:4]) # 和字符串一样,输出第三位和第四位元素
del list[1] # 删除第二个元素

def reverseWords(input):
    # 通过空格将字符串分隔为列表
    inputWords = input.split(" ")

    # 第三个参数为步长,负数表示逆向
    inputWords = inputWords[-1::-1] # 翻转列表
    # output = input[-1::-1] # 翻转字符串

    # 重新组合字符串
    output = ' '.join(inputWords)
    return output

if __name__=="__main__":
    input = 'I like runoob'
    rw = reverseWords(input)
    print(rw)

'''
Tuple(元组)
元组写在小括号()里,元素之间用逗号隔开,元素不能不能修改
'''

'''
Set (集合)
使用 {} 或者 set() 函数创建集合,注意空集合使用 set() 创建,{}用来创建空字典
'''
# set 可以进行集合运算
a = set('abcbsdvbso')
b = set('aldviobc')

print(a - b) # a 和 b 的差集
print(a | b) # a 和 b 的并集
print(a & b) # a 和 b 的交集
print(a ^ b) # a 和 b 中不同时存在的元素

'''
Dictionary(字典)
映射:键 -- 值
'''
dict = {'name':'runoob','code':1,'site':'www.baidu.com'}
dict['name'] = 'zhutou' # 更新元素
dict['age'] = 23 # 添加元素
# dict.clear() 清空字典
# del dict  删除字典

print(dict.keys()) # 输出所有键值
print(dict.values()) # 输出所有值
print({x:x**2 for x in (2,4,6)})

                                                                                                                                                                     猪头
                                                                                                                                                                  2020.3.21
发布了51 篇原创文章 · 获赞 4 · 访问量 2739

猜你喜欢

转载自blog.csdn.net/LZHPIG/article/details/105005219